@vkontakte/videoplayer-core 2.0.67 → 2.0.68

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/esnext.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
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/
2
+ * @vkontakte/videoplayer-core v2.0.68
3
+ * Thu, 01 Sep 2022 13:47:44 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-68/doc/
5
5
  */
6
- import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as a,fromEvent as r,assertNever as n,merge as o,tap as d,map as h,observableFrom as u,filterChanged as c,assertNonNullable as l,debounce as p,timeout as m,filter as f,mapTo as g,now as S,Observable as b,once as v,combine as y,abortable as T,getExponentialDelay as E,interval as $,throttle as w,Logger as k}from'@vkontakte/videoplayer-shared/esnext.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/esnext.esm.js';import A from'lodash/debounce';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{connection$=new t(void 0);castState$=new t(R.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(R.NOT_AVAILABLE);subscription=new i;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const e='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${e}`}),t.isDisabled||!e)return;var i;s(window.chrome?.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(i='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const s=document.createElement('script');s.setAttribute('src',i),s.onload=()=>t,s.onerror=()=>e,document.body.appendChild(s)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();a(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();a(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(r(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return n(t.sessionState)}}))).add(o(r(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),h((t=>t.castState))),u([i.getCastState()])).pipe(c(),h(B),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{const n=r===R.CONNECTED,o=s(this.connection$.getValue());if(n&&!o){const s=i.getCurrentSession();l(s);const r=s.getCastDevice(),n=s.getMediaSession()?.media.contentId;(a(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:r}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===R.CONNECTED?s(this.connection$.getValue())?R.CONNECTED:R.AVAILABLE:r)})))}initializeCastApi(){let t,e,i;try{t=cast.framework.CastContext.getInstance(),e=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{t.setOptions({receiverApplicationId:this.params.receiverApplicationId??e,autoJoinPolicy:i}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const B=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 N;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(N||(N={}));var M,O=(t,e=0,i=N.OFFSET_P)=>{switch(i){case N.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case N.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default: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'}(M||(M={}));const V={[M.Q_144P]:{width:256,height:144},[M.Q_240P]:{width:428,height:240},[M.Q_360P]:{width:640,height:360},[M.Q_480P]:{width:856,height:480},[M.Q_720P]:{width:1280,height:720},[M.Q_1080P]:{width:1920,height:1080},[M.Q_1440P]:{width:2560,height:1440},[M.Q_2160P]:{width:3840,height:2160},[M.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===M.INVARIANT;class z{state;transition;transitionStarted$=new e;transitionEnded$=new e;transitionUpdated$=new e;forceChanged$=new e;stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$);constructor(t){this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var Q;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Q||(Q={}));class W{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new z(Q.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case 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(h((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(h((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(r(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(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),a=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==a&&this.params.output.isBuffering$.next(a),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),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(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(r(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$,u(['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();this.videoState.getTransition()?.to!==Q.PAUSED&&t!==Q.PLAYING||(this.videoState.setState(Q.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==Q.PLAYING&&t!==Q.PAUSED||(this.videoState.setState(Q.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY)}handleRemoteStop(){this.videoState.getState()!==Q.STOPPED&&this.videoState.setState(Q.STOPPED)}handleRemoteVolumeChange(t){const e=this.params.output.volume$.getValue(),i={volume:t.volume??e.volume,muted:t.muted??e.muted};i.volume===e.volume&&i.muted==i.muted||this.params.output.volume$.next(i)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){const e=this.params.source;let i,a,r;switch(t){case D.MPEG:{const s=e[t];l(s);const n=Object.keys(s).sort(((t,e)=>t===e?0:t===M.INVARIANT?1:e===M.INVARIANT?-1:F(t,e)?1:-1))[0];l(n);const o=s[n];l(o),i=o,a='video/mp4',r=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS:case D.HLS_ONDEMAND:{const s=e[t];l(s),i=s.url,a='application/x-mpegurl',r=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 s=e[t];l(s),i=s.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS_LIVE:{const s=e[t];l(s),i=O(s.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case D.DASH_LIVE_WEBM:{const s=e[t];l(s),i=s.url,a='application/dash+xml',r=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 o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);o.contentUrl=i,o.streamType=r,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:h}=this.params.meta;return s(d)&&(o.metadata.title=d),s(h)&&(o.metadata.subtitle=h),o}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)}`})}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)if(s?.to===P.PAUSED||a.state!==C.Requested||t===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(a.position)}else t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.stop())}}class j{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 j{constructor(){super(),this.listeners||j.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:a=!1}=t;if(!X({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const a=new i(t,e);return s&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),a},r.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=r&&r.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const a=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,n(t,e)])}return n(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,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 at{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){const{url:e}=t.request,i=this.dashJsRequestQueue.get(e)??[];i.push(t),this.dashJsRequestQueue.set(e,i)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=st(s.request);if(a>=i.from&&r<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){if(t){const{request:e}=t,i=(this.dashJsRequestQueue.get(e.url)??[]).includes(t),s=this.activeRequests.get(e.url);i&&s&&s.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(st),s=i[0][0];let a=i[0][1];for(let t=1;t<i.length&&a<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===s?Math.max(a,s+this.params.minInitSize):Math.max(a,s+this.params.minDataSize);const r=new URL(t,location.href);r.searchParams.append('bytes',`${s}-${a}`);const n=r.toString(),o=new it,d=o.signal,h={url:t,from:s,to:a,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(h)));const u=t=>{throw this.params.onError?.({id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return et(n,{signal:d}).then((t=>{if(h.response=t,!t.ok||!t.body)return void this.onBigRequestError(h);const[e,i]=t.body.tee();this.params.onDownloadStream?.(i);const r=e.getReader(),n=parseInt(t.headers.get('Content-Length')??'',10)||a-s+1;h.data=new ArrayBuffer(n);const o=new Uint8Array(h.data),d=async({done:t,value:e})=>{t?this.onBigRequestProgress(h):e&&(o.set(e,h.loaded),h.loaded+=e.byteLength,this.onBigRequestProgress(h),await(r?.read().then(d,at.suppressStreamErrors).catch(u)))};r?.read().then(d,at.suppressStreamErrors).catch(u)}),at.suppressAbort).catch((t=>this.onBigRequestError(h,t))),h}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a,response:r}){if(!this.activeRequests.has(t)||!a)return;const n=this.dashJsRequestQueue.get(t)??[];for(const o of n){const{request:n}=o,[d,h]=st(n),u=d>=e&&h<=e+s,c=e>=d&&e+s<h,l=a.slice(d-e,Math.min(h-e+1,s));if((u||c)&&(n.requestStartDate=n.requestStartDate??new Date,n.firstByteDate=n.firstByteDate??new Date,n.bytesLoaded=l.byteLength,n.bytesTotal=i-e),u){n.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(this.dashJsRequestQueue.get(t)??[]).filter((t=>t!==o))),o.success?.(l,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';this.dashMetrics?.addHttpRequest(n,t,r?.status??200,e,[])}else c&&o.progress?.({loaded:s,total:i-e,lengthComputable:!0,stream:!0})}}onBigRequestError({url:t,from:e,to:i},s){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const a=this.dashJsRequestQueue.get(t)??[];for(const t of a){const[a,r]=st(t.request);(a>=e&&a<i||r>e&&r<=i)&&t?.error?.(t.request,String(s))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){if(!this.activeRequests.has(t))return;const s=this.dashJsRequestQueue.get(t)??[];for(const t of s){const[s,a]=st(t.request);(s>=e&&s<i||a>e&&a<=i)&&t?.abort?.(t.request)}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class rt{baseLoader;config;bigRequest;constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(rt.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;rt.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const nt=(t,e)=>{const i=new at(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new rt(a,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&&e?.()})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&e?.()}}}),!0)},dt=i=>{const a=new t(1/0),r=new e,n=new t(void 0),o=new t(void 0);let d=NaN,h=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{const e=Object.fromEntries(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in e||'x-playback-duration-millis'in e){const e=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),i=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*e??NaN;s(i)&&!isNaN(i)&&a.next(i)}const i=e['x-delivery-type']??L.HTTP1,r={1:!0,0:!1}[e['x-reused']]??void 0;n.next(i),o.next(r)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!h&&(h=!0,r.next(Date.now()-d)),i(...t)},d=Date.now(),h=!1}return e(t)}}}),!0),{playbackDuration$:a,ping$:r,connectionReused$:o,connectionType$:n}},ht=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},ut=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 ct=(t,e,s,{equal:r=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),h=e(),u=a(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();r(e,i)&&t.setState(e)}),o)),r(h,d)||(s(d),u&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),u&&t.setState(e.to)}),o)),c},lt=(t,e,i)=>ct(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),pt=(t,e,i,a)=>ct(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||t?.muted===e?.muted&&t?.volume===e?.volume,changed$:i,onError:a}),mt=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class ft{available$=new e;current$=new t(void 0);error$=new e;video;cueSettings;subscription=new i;externalTracks=new Map;connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const a=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(ct(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(h((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(ct(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:a})),this.subscription.add(ct(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(r(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(r(t,'addtrack'),r(t,'removetrack'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(o(r(t,'change'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),h((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>this.applyCueSettings(t.target?.activeCues??null);this.subscription.add(r(t,'addtrack').subscribe((t=>{t.track?.addEventListener('cuechange',e);const i=t=>{const e=t.target?.cues??null;e&&e.length&&(this.applyCueSettings(t.target?.cues??null),t.target?.removeEventListener('cuechange',i))};t.track?.addEventListener('cuechange',i)}))),this.subscription.add(r(t,'removetrack').subscribe((t=>{t.track?.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(ft.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&mt(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){l(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){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var gt=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class St{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}class bt{_buffer=[];_source;constructor(t){this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:a})=>{const r=s>=t&&s<e,n=a>=t&&a<e;r&&n||(r?i(e,a):n?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var vt=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(s=n,a=o,!i)return{from:s,to:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{from:s,to:a}};const yt=t=>{const i=e=>r(t,e).pipe(g(void 0)),a=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>r(t,e)))).pipe(h((()=>t.readyState<3)),c()),n=o(r(t,'progress'),r(t,'timeupdate')).pipe(h((()=>vt(t.buffered,t.currentTime)))),d=r(t,'volumechange').pipe(p(0),h((()=>({muted:t.muted,volume:t.volume})))),u=r(t,'error').pipe(h((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),l=r(t,'timeupdate').pipe(h((()=>t.currentTime))),m=new e;let S;return l.subscribe((e=>{t.loop&&s(S)&&s(e)&&S>=t.duration-.3&&e<=.3&&m.next(S),S=e})),{playing$:i('playing'),pause$:i('pause').pipe(f((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:m,error$:u,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:r(t,'durationchange').pipe(h((()=>t.duration))),isBuffering$:a,currentBuffer$:n,volumeState$:d}},Tt=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};let Et=!1,$t={};const wt=t=>{t($t)},kt=(t,e)=>{Et&&($t.meta=$t.meta??{},$t.meta[t]=e)};class At{name;constructor(t){this.name=t}next(t){if(!Et)return;$t.series=$t.series??{};const e=$t.series[this.name]??[];e.push([Date.now(),t]),$t.series[this.name]=e}}const Pt=new At('best_bitrate');class Dt{last;history={};recordSelection(t){this.history[t.id]=S()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const _t=(t,{container:e,throughput:i,tuning:r,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:h,current:u,history:c})=>{const l=r.usePixelRatio?window.devicePixelRatio??1:1,p=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*r.containerSizeFactor,height:e.height*l*r.containerSizeFactor},m=p&&G(p),f=r.considerPlaybackRate&&s(h)?h:1,g=t.filter((t=>!Y(t.quality))).sort(((t,e)=>q(t.quality,e.quality)?-1:1)),b=g.at(-1)?.quality,v=g.at(0)?.quality,y=a(n)||s(n.min)&&s(n.max)&&F(n.max,n.min)||s(n.min)&&v&&q(n.min,v)||s(n.max)&&b&&F(n.max,b),T=f*(E=d??.5,$=r.bitrateFactorAtEmptyBuffer,w=r.bitrateFactorAtFullBuffer,($-w)*Math.pow(2,-10*E)+w);var E,$,w;const k=g.filter((t=>{const e=!m||F(t.quality,m),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*T,c=r.lazyQualitySwitch&&s(r.minBufferToSwitchUp)&&u&&!Y(u.quality)&&(d??0)<r.minBufferToSwitchUp&&q(t.quality,u.quality),l=y||(a(n.max)||(p=t.quality,f=n.max,V[p].height<=V[f].height))&&(a(n.min)||((t,e)=>V[t].height>=V[e].height)(t.quality,n.min));var p,f;return e&&h&&!c&&l}))[0];k&&k.bitrate&&Pt.next(k.bitrate);const A=k??g[Math.ceil((g.length-1)/2)]??t[0],P=A&&c&&c.history[A.id]&&S()-c.history[A.id]<=r.trackCooldown&&(!c.last||A.id!==c.last.id);if(A?.id&&c&&!P&&c.recordSelection(A),P&&c?.last){const t=c.last;return c?.recordSwitch(t),t}return c?.recordSwitch(A),A};var Rt=t=>new URL(t).hostname;const It=(t,e=300)=>new b((i=>{const{width:a,height:r}=t.getBoundingClientRect();if(i.next({width:a,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let a,r;e.contentBoxSize&&e.contentBoxSize[0]?(r=e.contentBoxSize[0].blockSize,a=e.contentBoxSize[0].inlineSize):e.contentRect&&(a=e.contentRect.width,r=e.contentRect.height),s(a)&&s(r)&&i.next({width:a,height:r})}),e));return n.observe(t),()=>n.disconnect()})),Lt={};var Ct;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ct||(Ct={}));const xt=(t,e)=>new b((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Bt{subscription=new i;videoState=new z(Ct.DOWNLOADING_LIB);video;player;params;textTracksManager=new ft;videoTracks=[];frameRatesByFrameHeight={};isLive$=new t(void 0);maxSeekBackTime$=new t(1/0);availableFrom$=new t(void 0);elementSize$=new t(void 0);liveOffset=new St;destroyBigRequest;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Rt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${e?.toString?.()}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Lt.MediaPlayer=e.MediaPlayer,Lt.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Lt.MediaPlayer,'dashjs not loaded'),l(Lt.Debug,'dashjs not loaded'),this.player=Lt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter((t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Tt(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&&ut(this.player),ot(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:ht})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Ct.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(It(this.video),this.elementSize$),r(xt(this.player,'error').pipe(h((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),r(xt(this.player,'playbackError').pipe(h((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=xt(this.player,'qualityChangeRendered').pipe(f((({mediaType:t})=>'video'===t)),h((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));n.pipe(f(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(f((({to:t})=>t===Ct.STREAM_INITIALIZED)),v()).subscribe((()=>{this.subscription.add(ct(e.videoTrack,(()=>{const t=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track?.id}),(t=>{if(a(t))return;const e=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;e&&this.player.setQualityFor('video',e.qualityIndex)}),{changed$:n.pipe(h((t=>t?.id))),onError:i}))}),i)),this.subscription.add(ct(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),r(xt(this.player,'bufferStateChanged').pipe(f((({mediaType:t})=>'video'===t)),h((({state:t})=>'bufferStalled'===t))),t.isBuffering$),r(xt(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{const s=this.player.getDashMetrics(),a=s.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),r=s.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type')??L.HTTP1,n={1:!0,0:!1}[a]??void 0;this.params.output.httpConnectionType$.next(r),this.params.output.httpConnectionReused$.next(n),t.hostname$.next(Rt(i))})),r(xt(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=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===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(Ct.STREAM_INITIALIZED),this.videoState.startTransitionTo(Ct.READY)})),r(xt(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)})),r(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=_t(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));s?.bitrateInfo&&this.player.setQualityFor('video',s?.bitrateInfo.qualityIndex,!1)})),r(y({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(f(s))}).pipe(f((({isLive:t})=>t)),h((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const d=xt(this.player,'playbackTimeUpdated').pipe(h((({time:t})=>t??0)));r(y({availableFrom:this.availableFrom$.pipe(f(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(d.pipe(f((()=>!1===this.isLive$.getValue()))),t.position$),r(xt(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),r(xt(this.player,'playbackEnded'),t.endedEvent$),r(xt(this.player,'playbackProgress').pipe(h((()=>vt(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),r(xt(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Ct.PLAYING),U(e.playbackState,P.PLAYING)})),r(xt(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Ct.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(xt(this.player,'playbackPaused'),(()=>{this.videoState.setState(Ct.PAUSED),U(e.playbackState,P.PAUSED)})),r(xt(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===Ct.READY&&this.videoState.setState(Ct.READY)})),r(this.isLive$,t.isLive$),r(It(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,u(['init'])).pipe(p(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l,connectionType$:m,connectionReused$:S}=dt(this.player);r(m,this.params.output.httpConnectionType$),r(S,this.params.output.httpConnectionReused$),r(c,this.maxSeekBackTime$),r(l.pipe(v()),t.firstBytesEvent$),r(xt(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(y({isLive:this.isLive$,isShort:t.duration$.pipe(h((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),r(d.pipe(f((t=>t>this.params.tuning.insufficientBufferRuleMargin)),v()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(xt(this.player,'manifestLoaded').pipe(v()).subscribe((()=>{this.subscription.add(xt(this.player,'playbackPlaying').pipe(v(),g(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(lt(this.video,e.isLooped,i));const{volumeState$:b,looped$:T}=yt(this.video);this.subscription.add(pt(this.video,e.volume,b,i)),this.subscription.add(b.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(Ct.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Ct.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=O(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,N.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Ct.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Ct.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==Ct.DOWNLOADING_LIB&&t!==Ct.STREAM_INITIALIZED)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&t!==Ct.STOPPED&&e!==P.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case Ct.STOPPED:break;case Ct.PLAYING:case Ct.PAUSED:case Ct.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Ct.PLAYING:break;case Ct.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Ct.READY:this.play();break;case Ct.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Ct.PLAYING:this.pause(),this.liveOffset.pause();break;case Ct.PAUSED:break;case Ct.READY:this.videoState.setState(Ct.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case Ct.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Nt=t=>{switch(t){case'mobile':return M.Q_144P;case'lowest':return M.Q_240P;case'low':return M.Q_360P;case'sd':case'medium':return M.Q_480P;case'hd':case'high':return M.Q_720P;case'fullhd':case'full':return M.Q_1080P;case'quadhd':case'quad':return M.Q_1440P;case'ultrahd':case'ultra':return M.Q_2160P}},Mt=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function Ot(){return S()}function Ut(t){return Ot()-t}function Vt(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function qt(t,e,i,a){const r=window.XMLHttpRequest;let n,o,d,h,u,c=!1,p=0,m=!1,f='arraybuffer',g=7e3,S=2e3,b=()=>{if(c)return;l(h);const t=Ut(h);let e;if(t<S)return e=S-t,void setTimeout(b,e);S*=2,S>g&&(S=g),o&&o.abort(),o=new r,y()};const v=()=>{if(!c){if(--p>=0)return b(),void(a&&a());c=!0,u&&u(),i&&i()}},y=()=>{h=Ot(),o=new r,o.open('get',t);let i,s=0,a=0;const p=()=>(l(h),Math.max(h,Math.max(i||0,a||0)));if(n&&o.addEventListener('progress',(t=>{const e=Ot();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(c)return;l(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)}u&&u(),o&&e(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),m){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(a=Ot(),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)&&(S=t),s(e)&&(g=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(u=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,u&&u()}};return T}class Ft{intervals=[];currentRate=0;logger;constructor(t){this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const n=t.bytes*a/r;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:'warn'}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}}class Ht{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(t,e,i,s,a){this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=Ot(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=qt(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Ot()-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=Ot()}_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=Ot();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class Gt{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(t){this.params=t,this.chunkRateEstimator=new Ft(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Vt(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=Vt(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=>{this.destroyed||(e(`Video element error: ${t.error?.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,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ht(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:r}=this.params;let n=!1,o=null,d=null,h=null,u=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{h&&h.abort(),h=qt(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{h=null})).send()},f=(t,e,i)=>{l(this.filesFetcher),d?.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},g=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},S=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void g(1);const i=Ot()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const a=this.bufferStates[e];t=Math.min(t,a.buf),a.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,g(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else g(1)},v=t=>{let i;const a=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,h=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=e;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=i.dur.length-1;for(;r>=0&&(a-=i.dur[r],!(a<=0));--r);t=Math.min(r,i.dur.length-1-s),t=Math.max(t,0)}return h(t,!0)},m=(t,e,i)=>{u&&u.abort(),u=qt(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&S(d);let u=0;for(let t=0;t<i.dur.length;++t)u+=i.dur[t];u>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),r({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=a();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return h(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=a(),r=t?t.chunkIdx+1:0,n=r-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return h(r-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),h&&h.abort(),u&&u.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let r,d,h,c,g,S,T,E=v(t.jidxUrl),$=0;const w=()=>{g&&(clearTimeout(g),g=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=$+t,i=Ot(),s=Math.min(1e4,e-i);$=i;const a=()=>{u||p()&&E.seek((()=>{p()&&($=Ot(),k(),w())}))};s>0?g=window.setTimeout((()=>{this.paused?w():a()}),s):a()},k=()=>{let e;for(;e=E.nextChunk(c);)c=e,R(e);const i=E.nextChunk(h);if(i){if(h&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?w():(y(),this._initPlayerWith(t)));_(i)}else w()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let a,r,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=Ot(),h=i.currentTime;!this.paused&&i.buffered.length>1&&S===h&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),S!==h&&(S=h,T=d);const u=this._getBufferSizeSec();if(u>30)s(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(a=this.sourceBuffer.buffered.start(0),r=h,r-a>4&&this.sourceBuffer.remove(a,r-3)),o(1e3)}}},P=()=>{d&&r&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),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,h=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}P()}}),(()=>this._handleNetworkError()))},R=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{r=!0,P()})))};n=!0,E.seek((t=>{p()&&($=Ot(),t?(c=t,!a(e)||t.startTS>e?_(t):(h=t,k())):w())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),s(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Ot();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(n&&t>a&&Ut(r)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=Ot();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=qt(this.urlResolver.resolve(t,!0),e,i,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;Mt(e).then((e=>{e||t?.()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return t?.length?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var Yt;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Yt||(Yt={}));const zt=[Yt.PAUSED,Yt.PLAYING,Yt.READY],Qt=[Yt.PAUSED,Yt.PLAYING,Yt.READY];class Wt{subscription=new i;video;videoState=new z(Yt.STOPPED);dash;representations$=new t([]);textTracksManager=new ft;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new St;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const e=e=>{t.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:e})};o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Rt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=yt(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Yt.READY&&this.videoState.setState(Yt.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(Yt.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Yt.PLAYING)}),e)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),h((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(y({zeroTime:this.zeroTime$.pipe(f(s)),position:i.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(lt(this.video,this.params.desiredState.isLooped,e)).add(pt(this.video,this.params.desiredState.volume,i.volumeState$,e)).add(i.volumeState$.subscribe(this.params.output.volume$,e)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&V[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Yt.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case Yt.MANIFEST_READY:case Yt.READY:break;case Yt.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case Yt.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return n(t.to)}}),e)).add(o(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekState.stateChangeEnded$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(p(0)).subscribe(this.syncPlayback,e))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Gt({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){const t=this.representations$.getValue(),e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s(e)?e:_t(t.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.id,r=t.find((({track:t})=>t.id===a))?.representation;l(r,'Representations missing'),this.dash.startPlay(r,i),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(i)}setVideoTrack(t){const e=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;l(e,`No such representation ${t}`),this.dash.switchByName(e.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(O(this.params.source.url,i))}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,i=[];for(const t of e){const e=t.name??t.index.toString(10),s=Nt(t.name)??G(t.video),a=t.bitrate/1e3,r={...t.video};if(!s)continue;const n={id:e,quality:s,bitrate:a,size:r};i.push({track:n,representation:t})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map((({track:t})=>t))),this.videoState.getTransition()?.to===Yt.MANIFEST_READY&&this.videoState.setState(Yt.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=this.representations$.getValue().find((({representation:t})=>t===e))?.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e){if(Qt.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;s(t)&&this.setVideoTrack(t);const e=this.params.desiredState.autoVideoTrackSwitching.getTransition();e&&this.setAutoQuality(e.to)}if(a?.to!==P.PAUSED&&r.state===C.Requested&&zt.includes(t))this.seek(r.position-this.liveOffset.getTotalPausedTime());else switch(t){case Yt.STOPPED:return this.videoState.startTransitionTo(Yt.MANIFEST_READY),void this.dash.attachSource(O(this.params.source.url));case Yt.MANIFEST_READY:this.videoState.startTransitionTo(Yt.READY),this.prepare();break;case Yt.READY:return void(i===P.PAUSED?this.videoState.setState(Yt.PAUSED):i===P.PLAYING&&(this.videoState.startTransitionTo(Yt.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Yt.PAUSED)}))));case Yt.PLAYING:return void(i===P.PAUSED&&(this.videoState.startTransitionTo(Yt.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Yt.PAUSED:return void(i===P.PLAYING&&(this.videoState.startTransitionTo(Yt.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(Yt.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return n(t)}}}else t!==Yt.STOPPED&&(this.videoState.startTransitionTo(Yt.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Yt.STOPPED))}}var jt=t=>{const e=t.get('X-Delivery-Type'),i=t.get('X-Reused');return{type:null===e?L.HTTP1:e??void 0,reused:null===i?void 0:{1:!0,0:!1}[i]??void 0}},Jt=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)};class Kt{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(t,e=[],i,s,a,r){this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(l(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Xt{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(t){this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),e?.()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,c=0;const l=t=>{s(Xt._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=ht(p)),this._lastXhr=new Kt(p,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),a?.()}),(t=>{if(t.length-o>n&&l(t),0===u)return void(u=Date.now());c=t.length-h;const e=Date.now()-u;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,h=t.length,u=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),t?.()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Xt._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class Zt{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(t){this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=t.onDashCallback??(()=>{}),this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===i?.[1]?-1:1;e(i?.[2],s),e(i?.[3],s),e(i?.[4],s),e(i?.[5],s);return 3600*e(i?.[6],s)+60*e(i?.[7],s)+e(i?.[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=ht(i)),new Kt(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{const s=t.getElementsByTagName('SegmentBase')[0],o=s&&a(s,'indexRange').split('-'),d=s&&s.getElementsByTagName('Initialization')[0],h=d&&a(d,'range').split('-');if(!h||!o){const e=t.parentElement;if('text'===e?.getAttribute('contentType')){const s=t.getAttribute('id')??void 0,a=(i?i+'/':'')+t.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=e.getAttribute('lang')??void 0;a&&n.push({id:s,url:a,language:r})}return}const u=Number(t.attributes.getNamedItem('bandwidth')?.value),c=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=t.attributes.getNamedItem('frameRate')?.value??void 0;l=p?Tt(p):void 0,r.push({width:Number(t.attributes.getNamedItem('width')?.value),height:Number(t.attributes.getNamedItem('height')?.value),bandwidth:u,baseURL:c,failoverHosts:e,indexFrom:Number(o[0]),indexTo:Number(o[1]),initFrom:Number(h[0]),initTo:Number(h[1]),codecs:t.attributes.getNamedItem('codecs')?.value??void 0,mimeType:t.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*u/8,bufferLength:.1,name:t.attributes.getNamedItem('okQuality')?.value??void 0,id:t.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let n=a.getUint32(s,!1),o=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&a.getUint32(s,!1)),i=n+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/r,toTime:i/r,fromOffset:o,toOffset:e-1}),o=e,n=i}const h=t.refs[t.refs.length-1];h.toTime-h.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let r;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.to-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.to&&(a=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new Xt({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const a=this._findRef(e);if(a){if(i){this._isLastRef(a)&&e>=a.toTime&&(e=a.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:a.fromTime}this._appendVector[String(a.fromTime)]=t,this._stream.load(t,a.fromOffset,a.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const a=.1;if(s.toTime<i.to+a){const e=this._findRef(s.toTime);e&&e.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!a(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){const e=this._currentRepresentation?.refs;if(!e)return;if(Array.isArray(e)&&0===e.length)return void this._params.onError('emptyrefs','Empty refs');let i;for(let s=0;s<e.length;s++){const a=e[s];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!i||a.fromTime<i.fromTime)&&(i=a)}if(!i){const i=e[e.length-1];if(t>i.toTime)return i}return i}_isLastRef(t){const e=this._currentRepresentation?.refs;if(!e)return!1;const i=e[e.length-1];return t.fromTime===i.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var te;!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'}(te||(te={}));const ee=[te.PAUSED,te.PLAYING];class ie{videoState=new z(te.STOPPED);subscription=new i;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new ft;elementSize$=new t(void 0);dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(Rt(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new bt(this.video),this.dash=new Zt({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=yt(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,i));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.looped$,t.loopedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.playing$,t.firstFrameEvent$),l(d.canplay$,t.canplay$),this.subscription.add(d.seeking$.subscribe((()=>{a(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===te.PLAYING||this.videoState.getState()===te.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(lt(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(It(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(te.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(te.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(te.METADATA_LOADED)}),i)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(h((({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$,r(this.video,'progress')).pipe(h((()=>{const t=this.currentRepresentation$.getValue(),e=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.videoTrack.getState(),r=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),o=this.elementSize$.getValue(),d=n();let h;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&s(a))h=a;else{const i=Jt(this.video.buffered,1e3*this.video.currentTime),s=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(i/s,1);h=_t(e.map((({track:t})=>t)),{container:o,throughput:r,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:e.find((({representation:e})=>e===t))?.track})?.id}return s(h)?e.find((({track:t})=>t.id===h))?.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(y({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(f((t=>t.to===te.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(f(s))}).pipe(v()).subscribe((()=>this.videoState.setState(te.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(f(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=Jt(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(Rt(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=jt(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(v(),g(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$,u(['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)}}handleManifestReady=t=>{const e=[];for(const i of t){const t=i.name??i.id??i.height.toString(10),s=(i.name&&Nt(i.name))??G(i),a=i.bandwidth/1e3,r={width:i.width,height:i.height},n=i.fps;if(!s)continue;const o={id:t,quality:s,bitrate:a,size:r,fps:n};e.push({track:o,representation:i})}this.representations$.next(e),this.params.output.availableVideoTracks$.next(e.map((({track:t})=>t))),this.videoState.setState(te.MANIFEST_LOADED)};handleRepresentationPlay=t=>{const e=this.representations$.getValue().find((({representation:e})=>e===t))?.track;if(e){this.params.output.currentVideoTrack$.next(e);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(e.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t};seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(te.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)switch(s?.to!==P.PAUSED&&a.state===C.Requested&&ee.includes(t)&&this.seek(a.position,a.forcePrecise),t){case te.STOPPED:return this.videoState.startTransitionTo(te.MANIFEST_LOADED),void this.prepare();case te.MANIFEST_LOADED:return void this.videoState.startTransitionTo(te.INITIAL_REPRESENTATION_SELECTED);case te.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(te.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case te.METADATA_LOADED:return this.videoState.startTransitionTo(te.READY),void this.dash.updateRefsForCurrentTime();case te.READY:return void(i===P.PAUSED?(this.videoState.setState(te.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()));case te.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):s?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case te.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):s?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))}}var se,ae,re,ne,oe;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(se||(se={})),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'}(ae||(ae={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(re||(re={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(ne||(ne={})),function(t){t.MP4='mp4',t.WEBM='webm'}(oe||(oe={}));var de=(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 he='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 ue=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};let ce=!1;try{ce=ue()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??'',10)<16}catch(t){console.error(t)}class le{bufferFull$=new e;error$=new e;buffer;queue=[];currentTask=null;destroyed=!1;constructor(t){this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const a={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(a),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=ce&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}completeTask=()=>{try{if(this.currentTask){const t=this.currentTask.signal?.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown:t})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(t.signal?.aborted)return t.callback(!1),void this.pull();this.currentTask=t;const{operation:e}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===e&&this.bufferFull$.next(this.currentTask.data.byteLength),t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===e||this.error$.next({id:`BufferTaskQueue:${e}`,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 pe;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(pe||(pe={}));class me{throughputEstimator;requestQuic;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new it;subscription=new i;constructor({throughputEstimator:t,requestQuic:e}){this.throughputEstimator=t,this.requestQuic=e}onHeadersReceived(t){const{type:e,reused:i}=jt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest=T(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=ht(e));const i=yield et(e,{signal:this.abortAllController.signal}).catch(fe);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=T(this.abortAllController.signal,async function*(t,{rangeMethod:e=pe.HEADER,range:i,onProgress:s,priority:a='auto',signal:d,measureThroughput:h=!0}={}){let u=t;const c=new Headers;if(i)switch(e){case pe.HEADER:c.append('Range',`${i.from}-${i.to}`);break;case pe.PARAM:{const t=new URL(u,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),u=t.toString();break}default:n(e)}this.requestQuic&&(u=ht(u));let l=this.abortAllController.signal;if(d){const t=new it;if(this.subscription.add(o(r(this.abortAllController.signal,'abort'),r(d,'abort')).subscribe((()=>{try{t.abort()}catch(t){fe(t)}}))),this.abortAllController.signal.aborted||d.aborted)try{t.abort()}catch(t){fe(t)}l=t.signal}const p=S(),m=yield et(u,{priority:a,headers:c,signal:l}).catch(fe),f=S();if(this.throughputEstimator?.addRawRtt(f-p),!m)return null;if(!m.ok||!m.body)return Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));this.onHeadersReceived(m.headers);const g=parseInt(m.headers.get('Content-Length')??'',10)||i&&i.to-i.from+1||NaN;if(!g){const t=yield m.arrayBuffer();return this.throughputEstimator?.addRawSpeed(t.byteLength,S()-f),s?.(new DataView(t),t.byteLength),t}if(!s&&!h)return m.arrayBuffer();const[b,v]=m.body.tee(),y=b.getReader();h&&this.throughputEstimator?.trackStream(v);let E=0;const $=new ArrayBuffer(g),w=new Uint8Array($),k=new DataView($);let A=!1;const P=t=>{A=!0,fe(t)},D=T(l,async function*({done:t,value:e}){0===E&&this.lastRequestFirstBytes$.next(S()-p),l.aborted||(t?s?.(k,E):e&&(w.set(e,E),E+=e.byteLength,s?.(k,E),yield y?.read().then(D,P)))}.bind(this));return yield y?.read().then(D,P),A?null:$}.bind(this));async fetchRepresentation(t,e,i='auto'){const{type:s}=t;switch(s){case re.BYTE_RANGE:return await this.fetchByteRangeRepresentation(t,e,i)??null;case re.TEMPLATE:return await this.fetchTemplateRepresentation(t,i)??null;default:n(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=T(this.abortAllController.signal,async function*(t,e,i){if(t.type!==re.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,n,o=s,d=a,h=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,h=a+1===r,h&&(o=Math.min(r,s),d=Math.max(n,a))),o=Math.min(o,0);const u=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!u)return null;const c=new DataView(u,s-o,a-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(h&&void 0!==r&&void 0!==n)p=new DataView(u,r-o,n-r+1);else{const s=e.getIndexRange(l);if(s){const e=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,l);return{dataView:new DataView(u),segments:m}}.bind(this));fetchTemplateRepresentation=T(this.abortAllController.signal,async function*(t,e){if(t.type!==re.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:ne.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this))}const fe=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},ge=new TextDecoder('ascii'),Se=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=ge.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},be={validateData:t=>'ftyp'===ge.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Se(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),d=4294967295&a();let h=n/r*1e3,u=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=a(),e=t>>>31,s=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;i.push({status:ne.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=Se(a);if(s||='mdat'===i.id,!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var ve,ye;!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'}(ve||(ve={})),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'}(ye||(ye={}));const Te={[ve.EBML]:{type:ye.Master},[ve.EBMLVersion]:{type:ye.UnsignedInteger},[ve.EBMLReadVersion]:{type:ye.UnsignedInteger},[ve.EBMLMaxIDLength]:{type:ye.UnsignedInteger},[ve.EBMLMaxSizeLength]:{type:ye.UnsignedInteger},[ve.DocType]:{type:ye.String},[ve.DocTypeVersion]:{type:ye.UnsignedInteger},[ve.DocTypeReadVersion]:{type:ye.UnsignedInteger},[ve.Void]:{type:ye.Binary},[ve.Segment]:{type:ye.Master},[ve.SeekHead]:{type:ye.Master},[ve.Seek]:{type:ye.Master},[ve.SeekID]:{type:ye.Binary},[ve.SeekPosition]:{type:ye.UnsignedInteger},[ve.Info]:{type:ye.Master},[ve.TimestampScale]:{type:ye.UnsignedInteger},[ve.Duration]:{type:ye.Float},[ve.Tracks]:{type:ye.Master},[ve.Chapters]:{type:ye.Master},[ve.Cluster]:{type:ye.Master},[ve.Timestamp]:{type:ye.UnsignedInteger},[ve.SilentTracks]:{type:ye.Master},[ve.SilentTrackNumber]:{type:ye.UnsignedInteger},[ve.Position]:{type:ye.UnsignedInteger},[ve.PrevSize]:{type:ye.UnsignedInteger},[ve.SimpleBlock]:{type:ye.Binary},[ve.BlockGroup]:{type:ye.Master},[ve.EncryptedBlock]:{type:ye.Binary},[ve.Attachments]:{type:ye.Master},[ve.Tags]:{type:ye.Master},[ve.Cues]:{type:ye.Master},[ve.CuePoint]:{type:ye.Master},[ve.CueTime]:{type:ye.UnsignedInteger},[ve.CueTrackPositions]:{type:ye.Master},[ve.CueTrack]:{type:ye.UnsignedInteger},[ve.CueClusterPosition]:{type:ye.UnsignedInteger},[ve.CueRelativePosition]:{type:ye.UnsignedInteger},[ve.CueDuration]:{type:ye.UnsignedInteger},[ve.CueBlockNumber]:{type:ye.UnsignedInteger},[ve.CueCodecState]:{type:ye.UnsignedInteger},[ve.CueReference]:{type:ye.Master},[ve.CueRefTime]:{type:ye.UnsignedInteger}},Ee=t=>{const e=t.getUint8(0);let i=0;128&e?i=1:64&e?i=2:32&e?i=3:16&e&&(i=4);const s=$e(t,i),a=s in Te,r=a?Te[s].type:ye.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),h=((n&255>>o)<<8*(o-1))+$e(d),u=i+o;let c;return c=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:u,tagSize:u+h,value:c,valueSize:h}},$e=(t,e=t.byteLength)=>{switch(e){case 1:return t.getUint8(0);case 2:return t.getUint16(0);case 3:return t.getUint16(0)<<8|t.getUint8(2);case 4:return t.getUint32(0);case 5:return t.getUint32(0)<<8|t.getUint8(4);case 6:return t.getUint32(0)<<16|t.getUint16(4);case 7:return t.getUint32(0)<<32|t.getUint16(4)<<8|t.getUint8(6);case 8:return t.getUint32(0)<<32|t.getUint32(4)}return 0},we=(t,e)=>{switch(e){case ye.SignedInteger:return t.getInt8(0);case ye.UnsignedInteger:return $e(t);case ye.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case ye.String:return new TextDecoder('ascii').decode(t);case ye.UTF8:return new TextDecoder('utf-8').decode(t);case ye.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case ye.Master:case ye.Binary:return t;default:n(e)}},ke=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=Ee(s);if(!e(a))return;a.type===ye.Master&&ke(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},Ae=[ve.Info,ve.SeekHead,ve.Tracks,ve.Chapters,ve.Cluster,ve.Cues,ve.Attachments,ve.Tags],Pe=[ve.Timestamp,ve.SilentTracks,ve.SilentTrackNumber,ve.Position,ve.PrevSize,ve.SimpleBlock,ve.BlockGroup,ve.EncryptedBlock],De={validateData:t=>{if(t.getUint32(0)!==ve.EBML)return!1;let e,i,s;const a=Ee(t);return ke(a.value,(({tag:t,type:a,value:r})=>(t===ve.EBMLReadVersion?e=we(r,a):t===ve.DocType?i=we(r,a):t===ve.DocTypeReadVersion&&(s=we(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,a,r,n,o=!1,d=!1,h=!1;return ke(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===ve.SeekID){const t=we(c,u);n=$e(t)}else t!==ve.SeekPosition&&(n=void 0);return t===ve.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===ve.Info?o=!0:t===ve.SeekHead?d=!0:t===ve.TimestampScale?s=we(c,u):t===ve.Duration?a=we(c,u):t===ve.SeekPosition&&n===ve.Cues?r=we(c,u):o&&d&&Ae.includes(t)&&(h=!0),!h})),l(e,'Failed to parse webm Segment start'),l(i,'Failed to parse webm Segment end'),l(a,'Failed to parse webm Segment duration'),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:r}},getIndexRange:t=>{if(a(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,a=!1;const r=t=>s(t.time)&&s(t.position),n=[];let o;return ke(t,(({tag:t,type:e,value:s})=>{switch(t){case ve.Cues:i=!0;break;case ve.CuePoint:o&&r(o)&&n.push(o),o={};break;case ve.CueTime:o&&(o.time=we(s,e));break;case ve.CueTrackPositions:break;case ve.CueClusterPosition:o&&(o.position=we(s,e));break;default:i&&Ae.includes(t)&&(a=!0)}return!(i&&a)})),o&&r(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:a}=t,r=n[i+1];return{status:ne.NONE,time:{from:s,to:r?r.time:e.segmentDuration},byte:{from:e.segmentStart+a,to:r?e.segmentStart+r.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{ke(t,(s=>s.tag===ve.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Pe.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||=[ve.SimpleBlock,ve.BlockGroup,ve.EncryptedBlock].includes(s.tag)),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class _e{onLastSegment$=new t(!1);fullyBuffered$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;gaps=[];subscription=new i;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new it;destroyAbortController=new it;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;constructor(t,e,i,s,{fetcher:a,tuning:r,getCurrentPosition:o}){switch(this.fetcher=a,this.tuning=r,this.forwardBufferTarget=r.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case oe.MP4:this.containerParser=be;break;case oe.WEBM:this.containerParser=De;break;default:n(i)}this.initData=new Map(s.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(s.map((t=>[t.id,t]))),this.kind=t,this.mediaSource=e,this.sourceBuffer=null}startWith=T(this.destroyAbortController.signal,async function*(t){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new le(this.sourceBuffer),this.subscription.add(r(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(r(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),a=this.segments.get(e.id);if(l(i,'No init buffer for starting representation'),l(a,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let n=0;for(const t of a)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));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);l(e,`No such representation ${t}`);let i=this.initData.get(t);if(a(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 r=this.getCurrentPosition();s(r)&&this.maintain(r)}.bind(this));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(a(this.downloadingRepresentationId)||a(this.playingRepresentationId)||a(this.sourceBuffer))return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(l(e,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,i=Jt(this.sourceBuffer.buffered,t),a=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(r=a)}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,r),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&s)if(n.includes(s))t='high';else{const e=n.at(0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===ne.FED&&!n.length&&Jt(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=i.at(-1);o&&o.status===ne.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){const e=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!e)return;const i=this.segments.get(e);if(!i)return;return i.find((e=>e.time.from<=t&&e.time.to>=t))?.time.from??void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===ne.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==re.BYTE_RANGE)return t.slice(s,s+1);const a=t;let r=0;const n=[];for(let t=s;t<a.length&&r<=this.tuning.dash.segmentRequestSize;t++){const e=a[t];if(r+=e.byte.to+1-e.byte.from,e.status!==ne.NONE)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,a,r=t;const{type:o}=e.segmentReference;switch(o){case re.BYTE_RANGE:s=e.segmentReference.url,a={from:t.at(0).byte.from,to:t.at(-1).byte.to};break;case re.TEMPLATE:{const i=t.at(0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),r=[i];break}default:n(o)}for(const t of r)t.status=ne.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:pe.PARAM,range:a,onProgress:(t,i)=>{if(!d.aborted)try{this.onSomeDataLoaded(t,e.id,a?a.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){let e=!1;const i=this.getCurrentPosition();if(this.sourceBuffer&&s(i)){e=Jt(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,e||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,a){if(!this.activeSegments.size)return;const r=t=>{this.abortSegment(t.segment)},n=t=>{this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=ne.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const i of this.representations.values())if(i.id!==e)for(const e of this.segments.get(i.id)??[])e.status===ne.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=ne.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,h=t.byteLength;for(const o of this.activeSegments){const{segment:u}=o,c=d===re.BYTE_RANGE,l=c?u.byte.to-u.byte.from+1:h;if(o.representationId!==e)continue;if(!(!c||u.byte.from>=i&&u.byte.to<i+t.byteLength))continue;if(a.aborted){r(o);continue}const p=c?u.byte.from-i:0,m=p<s,f=(c?u.byte.to-i:t.byteLength)<=s;if(u.status===ne.DOWNLOADING&&m&&f){u.status=ne.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,l);this.sourceBufferTaskQueue.append(e,a).then((t=>t&&!a.aborted?n(o):r(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(l,s-p),o.loadedBytes>o.fedBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.fedBytes,o.loadedBytes-o.fedBytes),i=o.loadedBytes===l?e:this.containerParser.parseFeedableSegmentChunk(e);i?.byteLength&&(u.status=ne.PARTIALLY_FED,o.fedBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,a).then((t=>{!t||a.aborted?r(o):o.fedBytes===l&&n(o)})))}}}abortSegment(t){t.status===ne.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=ne.NONE)),t.status=ne.NONE):t.status=ne.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const a=s instanceof Promise;e||=a,null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=he((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,e='auto',i=!1){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',a=(!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,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,a),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,a),a}async pruneBuffer(t){const e=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||a(e))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let s=0,r=1/0,n=-1/0,o=!1;const d=t=>{r=Math.min(r,t.time.from),n=Math.max(n,t.time.to);const e='size'in t?t.size??0:t.byte.to-t.byte.from;s+=e};for(const a of i){if(a.time.to>=e||s>=t)break;a.status===ne.FED&&d(a)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=1/0,n=-1/0;for(const a of i){if(a.time.from<e+this.forwardBufferTarget||s>t)break;a.status===ne.FED&&d(a)}}return o=isFinite(r)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(r/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),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=he((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(a(this.sourceBuffer)||a(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!==ne.FED||i||(s.status=ne.NONE)}}}const Re=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===i?.[1]?-1:1;return 24*e(i?.[5],s)*60*60*1e3+60*e(i?.[6],s)*60*1e3+60*e(i?.[7],s)*1e3+1e3*e(i?.[8],s)},Ie=(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)=>a(e)?t:a(i)?e:e.padStart(parseInt(i,10),'0')))}return i},Le=['timeupdate','progress','play','seeked','stalled'];var Ce,xe;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Ce||(Ce={}));class Be{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new i;fetcher;state$=new z(Ce.NONE);currentVideoRepresentation$=new t(void 0);error$=new e;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);forceEnded$=new e;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new it;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new me({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=T(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(Ce.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 a;try{a=((t,e)=>{const i={video:[],audio:[],text:[]},a=(new DOMParser).parseFromString(t,'application/xml').children[0],r=a.getElementsByTagName('Period')[0],n=r.children;let o;const d=a.getAttribute('mediaPresentationDuration'),h=r.getAttribute('duration');if(d)o=Re(d);else if(h){const t=Re(h);s(t)&&(o=t)}let u=0;const c=a.getAttribute('profiles')?.split(',')??[],l=c.includes(ae.WEBM_AS_IN_FFMPEG)||c.includes(ae.WEBM_AS_IN_SPEC)?oe.WEBM:oe.MP4;for(const t of n){const s=t.getAttribute('mimeType'),a=t.getAttribute('codecs'),r=t.getAttribute('contentType')??s?.split('/')[0],n=t.getAttribute('profiles')?.split(',')??[],d=t.querySelectorAll('Representation');if('text'!==r)for(const h of d){const d=h.getAttribute('mimeType')??s,l=h.getAttribute('codecs')??a??'',p=h.getAttribute('contentType')??d?.split('/')[0]??r,m=t.getAttribute('profiles')?.split(',')??[],f=parseInt(h.getAttribute('width')??'',10),g=parseInt(h.getAttribute('height')??'',10),S=parseInt(h.getAttribute('bandwidth')??'',10)/1e3,b=h.getAttribute('frameRate')??'',v=h.getAttribute('quality')??void 0,y=b?Tt(b):void 0,T=`${h.getAttribute('id')??(u++).toString(10)}@${'video'===p?`${g}p`:'audio'===p?`${S}Kbps`:l}`,E=h.querySelector('BaseURL')?.textContent?.trim()??'',$=new URL(E,e).toString(),w=[...c,...n,...m];let k;const A=h.querySelector('SegmentBase'),P=h.querySelector('SegmentTemplate');if(A){const t=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[r,n]=a?a.split('-').map((t=>parseInt(t,10))):[],o=a?{from:r,to:n}:void 0;k={type:re.BYTE_RANGE,url:$,initRange:s,indexRange:o}}else{if(!P)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:h.getAttribute('id')??void 0,bandwidth:h.getAttribute('bandwidth')??void 0},e=parseInt(P.getAttribute('timescale')??'',10),i=P.getAttribute('initialization')??'',s=P.getAttribute('media'),a=parseInt(P.getAttribute('startNumber')??'',10)??1,r=Ie(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const n=P.querySelectorAll('SegmentTimeline S')??[],o=[];let d=a,u=0;for(const i of n){const a=1e3*parseInt(i.getAttribute('d')??'',10),r=parseInt(i.getAttribute('r')??'',10)||0,n=parseInt(i.getAttribute('t')??'',10)??void 0;for(let i=0;i<r+1;i++){const i=Ie(s,{...t,segmentNumber:d.toString(10),segmentTime:n.toString(10)}),r=n?n/e:u;u+=a/e;const h=u;d++,o.push({time:{from:r,to:h},url:i})}}k={type:re.TEMPLATE,baseUrl:$,initUrl:r,segments:o}}}if(!p||!d)continue;const D={video:se.VIDEO,audio:se.AUDIO,text:se.TEXT}[p];D&&i[D].push({id:T,kind:D,segmentReference:k,profiles:w,duration:o,bitrate:S,mime:d,codecs:l,width:f,height:g,fps:y,quality:v})}}return{duration:o,container:l,representations:i}})(i??'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!a)return null;const r=({mime:e,codecs:i})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${i}"`));return this.manifest={...a,representations:Object.fromEntries(Object.entries(a.representations).map((([t,e])=>[t,e.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(Ce.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this));initRepresentations=T(this.destroyController.signal,async function*(t,e){l(this.manifest),l(this.element),this.state$.startTransitionTo(Ce.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new _e(se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new _e(se.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 a=o(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(h((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),n=o(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(h((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(o(this.forceEnded$,y({allBuffersFull:a,someBufferEnded:n}).pipe(f((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{this.source?.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',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=>this.source?.addEventListener('sourceopen',t)))),s(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s(e)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Ce.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...Le.map((t=>r(this.element,t))),r(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(r(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(r(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&de(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this));async switchRepresentation(t,e){return{[se.VIDEO]:this.videoBufferManager,[se.AUDIO]:this.audioBufferManager,[se.TEXT]:null}[t]?.switchTo(e)}seek(t,e){let i;l(this.element),l(this.videoBufferManager),i=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(this.videoBufferManager.findSegmentStartTime(t)??t,this.audioBufferManager?.findSegmentStartTime(t)??t),de(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ce.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager?.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager?.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=$(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=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'}(xe||(xe={}));const Ne=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?Nt(r):void 0)??G({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Me=(t,e,i)=>{const s=e.indexOf(i);return t.at(Math.round(t.length*s/e.length))??t.at(-1)};class Oe{subscription=new i;videoState=new z(xe.STOPPED);video;player;params;elementSize$=new t(void 0);textTracksManager=new ft;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Dt;constructor(t){this.params=t,this.video=gt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Rt(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Be({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=yt(this.video),a=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,a));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),v(),g(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(lt(this.video,e.isLooped,a)),this.subscription.add(pt(this.video,e.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),n(It(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(xe.PLAYING),U(e.playbackState,P.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(xe.PAUSED),U(e.playbackState,P.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===xe.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(f((({to:t})=>t===Ce.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(xe.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$,r(this.video,'progress')).subscribe((()=>{const i=this.player.state$.getState(),s=this.player.state$.getTransition();if(i===Ce.NONE||!this.videoTracks.length)return;const a=i===Ce.MANIFEST_LOADED&&!s,r=i===Ce.REPRESENTATION_SELECTED&&!s,n=e.autoVideoTrackSwitching.getState(),o=e.videoTrack.getState(),h=this.videoTracks.find((({track:{id:t}})=>t===o))?.track,u=t.currentVideoTrack$.getValue(),c=Jt(this.video.buffered,1e3*this.video.currentTime),p=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(c/Math.min(p,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),f=Math.max(h&&!n?this.audioRepresentations.get(h.id)?.bitrate??0:0,u?this.audioRepresentations.get(u.id)?.bitrate??0:0),g=_t(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),reserve:f,forwardBufferHealth:m,current:u,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=n?g??h:h??g;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(n),this.player.setBufferTarget(p)),a){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;l(t),this.player.initRepresentations(t.id,this.audioRepresentations.get(t.id)?.id)}else if(r){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(se.VIDEO,t.id).catch(d),e&&this.player.switchRepresentation(se.AUDIO,e.id).catch(d)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),h((t=>t&&this.videoTracks.find((({representation:{id:e}})=>e===t))?.track))).subscribe(t.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,e,t);const m=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,u(['init'])).pipe(p(0));this.subscription.add(m.subscribe(this.syncPlayback,a))}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=Ne(t);if(s){this.videoTracks.push({track:s,representation:t});const a=Me(e,i,t);a&&this.audioRepresentations.set(t.id,a)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(s.state===C.Requested&&i?.to!==P.PAUSED&&t!==xe.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===xe.STOPPED)return this.videoState.startTransitionTo(xe.READY),void this.prepare();switch(t){case xe.READY:return void(e===P.PAUSED?(this.videoState.setState(xe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(xe.PLAYING),this.playIfAllowed()));case xe.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(xe.PAUSED),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case xe.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(xe.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==xe.STOPPED&&(this.videoState.startTransitionTo(xe.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(xe.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(xe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Ue={};var Ve;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ve||(Ve={}));const qe=(t,e)=>new b((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class Fe{subscription=new i;videoState=new z(Ve.INITIALIZING);video;params;hls;textTracksManager=new ft;trackLevels=new Map;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Rt(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(Ue.Hls=e.default,Ue.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Ue.Hls,'hls.js not loaded'),this.hls=new Ue.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Ve.STOPPED)}subscribe(){l(Ue.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})},r=yt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadStart$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),this.subscription.add(lt(this.video,t.isLooped,i)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.hls,Ue.Events.ERROR).subscribe((t=>{t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${t.err?.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Ve.PLAYING),U(t.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ve.PAUSED),U(t.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ve.READY&&this.videoState.setState(Ve.READY),this.videoState.getState()===Ve.PLAYING&&this.playIfAllowed()}),i)),n(qe(this.hls,Ue.Events.MANIFEST_PARSED).pipe(h((({levels:t})=>t.reduce(((t,e)=>{const i=e.name||e.height.toString(10),{width:s,height:a}=e,r=Nt(e.attrs.QUALITY??'')??G({width:s,height:a});if(!r)return t;const n=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,o={id:i.toString(),quality:r,bitrate:e.bitrate/1e3,size:{width:s,height:a},fps:n};return this.trackLevels.set(i,{track:o,level:e}),t.push(o),t}),[])))),e.availableVideoTracks$),n(qe(this.hls,Ue.Events.LEVEL_LOADING).pipe(h((({url:t})=>Rt(t)))),e.hostname$),this.subscription.add(ct(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=>Array.from(this.trackLevels.values()).find((({level:e})=>e===t))?.track,c=qe(this.hls,Ue.Events.LEVEL_SWITCHED).pipe(h((({level:t})=>d(this.hls.levels[t]))));c.pipe(f(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(ct(t.videoTrack,(()=>d(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(a(t))return;const e=this.trackLevels.get(t)?.level;if(!e)return;const i=this.hls.levels.indexOf(e),s=this.hls.currentLevel,r=this.hls.levels[s];!r||e.bitrate>r.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:c.pipe(h((t=>t?.id))),onError:i})),n(r.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$,u(['init'])).pipe(p(0));this.subscription.add(m.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(t!==Ve.INITIALIZING)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case Ve.STOPPED:break;case Ve.READY:case Ve.PLAYING:case Ve.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Ve.PLAYING:break;case Ve.STOPPED:this.prepare();break;case Ve.READY:case Ve.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case Ve.PAUSED:break;case Ve.STOPPED:this.prepare();break;case Ve.READY:this.videoState.setState(Ve.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case Ve.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}};prepare(){this.videoState.startTransitionTo(Ve.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Ve.PLAYING);await Mt(this.video)||(this.videoState.setState(Ve.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Ve.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(Ve.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}}const He=t=>{let e=null;if(t.QUALITY&&(e=Nt(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=G({width:i,height:s})}return e??null},Ge=async(t,e=t)=>{const i=await et(t),s=(await i.text()).split('\n'),a=[];for(let t=0;t<s.length;t++){const i=s[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!i)continue;const r=Object.fromEntries(i[1].split(',').map((t=>t.split('=')))),n=r.QUALITY??`stream-${r.BANDWIDTH}`,o=He(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let u;if(r.RESOLUTION){const[t,e]=r.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(u={width:t,height:e})}const c=new URL(s[++t],e).toString();o&&a.push({id:n,quality:o,url:c,bandwidth:d,size:u,fps:h})}return a};var Ye,ze,Qe;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Ye||(Ye={}));class We{subscription=new i;videoState=new z(Ye.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);maxSeekBackTime$;liveOffset=new St;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:M.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Ge(O(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([i,...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(Rt(this.params.source.url)),this.maxSeekBackTime$=new t(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},a=yt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(pt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Ye.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ye.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ye.READY&&this.videoState.setState(Ye.READY),this.videoState.getState()===Ye.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),h((t=>-t/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Rt(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Ye.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(a.loadedData$.subscribe((()=>{const t=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(t||void 0)}),i)),this.subscription.add(y({startTime:this.manifestStartTime$.pipe(f(s)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,u(['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(a(t))return;const e=O(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=>{a(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Ye.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()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Ye.STOPPED&&(this.videoState.startTransitionTo(Ye.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(Ye.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===Ye.STOPPED)return this.videoState.startTransitionTo(Ye.READY),void this.prepare();if(s||a){const t=this.videoState.getState();return this.videoState.setState(Ye.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if(i?.to!==P.PAUSED&&r.state===C.Requested)return this.videoState.startTransitionTo(Ye.READY),this.seek(r.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Ye.READY:return void(e===P.PAUSED?(this.videoState.setState(Ye.PAUSED),this.liveOffset.pause(),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Ye.PLAYING),this.playIfAllowed()));case Ye.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Ye.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Ye.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Ye.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):i?.to===P.PAUSED&&(U(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Ye.CHANGING_MANIFEST:break;default:return n(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(ze||(ze={}));class je{subscription=new i;videoState=new z(ze.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video);const e={id:'master',quality:M.INVARIANT,url:this.params.source.url};this.manifests$.next([e]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Rt(this.params.source.url)),Ge(this.params.source.url).then((t=>{this.manifests$.next([e,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},a=yt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),r(a.seeked$,t.seekedEvent$),this.subscription.add(lt(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(ze.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(ze.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ze.READY&&this.videoState.setState(ze.READY),this.videoState.getState()===ze.PLAYING&&this.playIfAllowed()}),i).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Rt(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===ze.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===C.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['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();a(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(ze.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==ze.STOPPED&&(this.videoState.startTransitionTo(ze.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(ze.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===ze.STOPPED)return this.videoState.startTransitionTo(ze.READY),void this.prepare();if(s||a){const t=this.videoState.getState();this.videoState.setState(ze.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case ze.READY:return void(e===P.PAUSED?(this.videoState.setState(ze.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(ze.PLAYING),this.playIfAllowed()));case ze.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(ze.PAUSED),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case ze.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(ze.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));case ze.CHANGING_MANIFEST:break;default:return n(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Qe||(Qe={}));class Je{subscription=new i;videoState=new z(Qe.STOPPED);video;trackUrls={};params;textTracksManager=new ft;constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=yt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),r(a.seeked$,t.seekedEvent$),this.subscription.add(lt(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Qe.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Qe.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Qe.READY&&this.videoState.setState(Qe.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&s(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===Qe.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$,u(['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(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();l(t,'MpegProvider: track is not selected');let{url:e}=this.trackUrls[t];l(e,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(e=ht(e)),this.video.setAttribute('src',e),this.video.load(),this.params.output.hostname$.next(Rt(e))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Qe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==Qe.STOPPED&&(this.videoState.startTransitionTo(Qe.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Qe.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(t===Qe.STOPPED)return this.videoState.startTransitionTo(Qe.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case Qe.READY:return void(e===P.PAUSED?(this.videoState.setState(Qe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Qe.PLAYING),this.playIfAllowed()));case Qe.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Qe.PAUSED),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Qe.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Qe.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}}class Ke{iterator;current;constructor(t){this.iterator=t[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const Xe=ue(),Ze=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),ti=document.createElement('video'),ei={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(ti.canPlayType?.('application/x-mpegurl')||ti.canPlayType?.('vnd.apple.mpegURL'))},ii={mp4:Boolean(ti.canPlayType?.('video/mp4')),webm:Boolean(ti.canPlayType?.('video/webm'))},si={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},ai=(si.h264||si.h265)&&si.aac,ri=!Xe,ni=Ze||Xe,oi=!ei.hls||!ni;const di=3e4,hi=18e4,ui=3,ci=100,li={cacheDuration:12e4},pi={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},mi={maxPausedTime:3e4},fi={maxPausedTime:3e4};class gi{current$=new t({type:void 0});providerError$=new e;noAvailableProvidersError$=new e;providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,canplay$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)};subscription=new i;screenFormatsIterator;chromecastFormatsIterator;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:e}=this.params.tuning,i=e.length?[...t.screenFormatsPriority.filter((t=>!e.includes(t))),...t.screenFormatsPriority.filter((t=>e.includes(t)))]:t.screenFormatsPriority;this.screenFormatsIterator=new Ke(i.filter((e=>s(t.sources[e]))).filter((t=>{switch(t){case D.DASH:return ei.mse&&ii.mp4&&ai&&ri;case D.DASH_SEP:case D.DASH_SEP_VK:return ei.mse&&ii.mp4&&ai;case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.DASH_LIVE_WEBM:return ei.mse&&ii.webm&&si.vp9&&si.opus;case D.DASH_LIVE:return ei.mse&&ii.mp4&&ai;case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:return ei.mse&&ii.mp4&&ai;case D.HLS:case D.HLS_LIVE:case D.HLS_ONDEMAND:return ei.hls&&ii.mp4&&ni;case D.HLS_JS:return ei.mse&&ii.mp4&&ai&&oi;case D.MPEG:return ii.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new Ke(t.chromecastFormatsPriority.filter((e=>s(t.sources[e]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),e=this.chooseFormat(t);if(a(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;l(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case _.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,a={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 l(i),new ie({...a,source:i,config:li})}case D.DASH_ONDEMAND_VK:case D.DASH_SEP_VK:case D.DASH_WEBM_VK:{const i=e[t];return l(i),new Oe({...a,source:i})}case D.DASH_SEP:case D.DASH_WEBM:case D.DASH_ONDEMAND:case D.DASH_LIVE_WEBM:{const i=e[t];return l(i),new Bt({...a,source:i,format:t,config:fi})}case D.HLS:case D.HLS_ONDEMAND:{const i=e[t];return l(i),new je({...a,source:i})}case D.HLS_LIVE:{const i=e[t];return l(i),new We({...a,source:i,config:mi})}case D.HLS_JS:{const i=e[t];return l(i),new Fe({...a,source:i})}case D.MPEG:{const i=e[t];return l(i),new Je({...a,source:i})}case D.DASH_LIVE:{const i=e[t];return l(i),new Wt({...a,source:i,config:pi})}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:a}=this.params,r=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new W({connection:n,meta:a,container:i,source:e,format:t,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_.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=[],a=0;const r=new i;var n;return r.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:di,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(f((({type:t})=>void 0!==t)))},new b((t=>{const s=new i,a=n.desiredPlaybackState$.stateChangeStarted$.pipe(h((({from:t,to:e})=>`${t}-${e}`))),r=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let u=0,c='unknown';return s.add(a.subscribe((t=>{u&&window.clearTimeout(u),c=t,u=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(r.subscribe((()=>{window.clearTimeout(u),c='provider change',u=0}))),s.add(o.subscribe((()=>{u&&(window.clearTimeout(u),u=window.setTimeout((()=>d.next(c)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(u),s.unsubscribe()}}))).pipe(h((t=>({id:`ProviderHangup:${t}`,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),r.add(this.providerError$.pipe(w(ci,{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[a])&&e<t[a]+hi?(t=[],this.switchToNextProvider()):(t[a]=e,this.reinitProvider()),a=(a+1)%ui}))),r}}const Si=(t,e,i)=>i*e+(1-i)*t;class bi{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const i=e.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new At(`raw_${i}`),this.smoothedSeries$=new At(`smoothed_${i}`),this.reportedSeries$=new At(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=(this.pastMeasures[t]-this.smoothed)**2,i++);e/=i;const s=Math.sqrt(e),r=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=Si(this.slow,t,this.params.emaAlphaSlow),this.fast=Si(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>r||this.smoothed<n||(a(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 vi;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(vi||(vi={}));const yi=new Map;let Ti=vi.RUNTIME;const Ei=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Ei,'test'),localStorage.removeItem(Ei),Ti=vi.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Ei),Ti=vi.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Ti=vi.RUNTIME}}})();const $i=(t,e)=>{switch(Ti){case vi.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case vi.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case vi.RUNTIME:return void yi.set(t,e);default:n(Ti)}},wi=window.navigator.connection,ki=()=>{const t=wi?.downlink;if(s(t)&&10!==t)return 1e3*t},Ai=()=>{const t=wi?.rtt;if(s(t)&&3e3!==t)return t},Pi=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Di{throughput;rtt;subscription=new i;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=Di.load('one_video_throughput')||(e.useBrowserEstimation?ki():void 0)||5e3,a=Di.load('one_video_rtt')??(e.useBrowserEstimation?Ai():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(Pi(i,a,e.rttPenaltyRequestSize)),this.throughput=new bi({initial:i,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new bi({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=ki();t&&this.throughput.next(t);const e=Ai();s(e)&&this.rtt.next(e)};wi&&'onchange'in wi&&this.subscription.add(r(wi,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{$i('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{$i('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(h((({throughput:t,rtt:i})=>Pi(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=S();const a=new i;switch(this.subscription.add(a),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:a.add(r(t,'progress').pipe(v()).subscribe((t=>{e=t.loaded,s=S()})));break;case 1:case 0:a.add(r(t,'loadstart').subscribe((()=>{e=0,s=S()})))}a.add(r(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,a=S(),r=t-e,n=a-s;this.addRawSpeed(r,n,1)}this.concurrentDownloads.delete(t),a.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=S();let a=0,r=S();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:d,value:h})=>{d?(this.addRawSpeed(i,S()-s,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,a+=h.byteLength,a>=this.tuningConfig.streamMinSampleSize&&S()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,S()-r,this.concurrentDownloads.size),a=0,r=S()),await(e?.read().then(o,n)))};this.concurrentDownloads.add(t),e?.read().then(o,n)}addRawSpeed(t,e,i=1){if(Di.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){const e=(t=>{switch(Ti){case vi.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case vi.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case vi.RUNTIME:return yi.get(t);default:n(Ti)}})(t);if(s(e))return parseInt(e,10)??void 0}}const _i={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 Ri=(t=(t=>t))=>({playbackState:e,seekState:s,playbackAbort$:r,looped$:n,position$:d})=>new b((u=>{let c;const l=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})=>t.state===C.Requested&&(e.getTransition()?.from??e.getState())===P.PLAYING))),g=s.stateChangeEnded$.pipe(f((({from:t,to:i})=>t.state===C.Applying&&i.state===C.None&&(e.getTransition()?.from??e.getState())===P.PLAYING))),S=o(l,g).pipe(h((()=>t(d.getValue())))),b=o(o(p,m,r).pipe(h((()=>t(d.getValue())))),n.pipe(h(t)));return(new i).add(S.subscribe((e=>{c=t(e)}))).add(b.subscribe((e=>{const i=t(e);if(a(c)||c===i)return;const s={from:c,to:i};c=void 0,u.next(s)})))})),Ii=Ri((t=>t)),Li=Ri((t=>Math.round(1e3*t)+Date.now())),Ci={[_.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 xi{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new k;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;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({})};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)};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};experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:wt};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(_i)){const s=_i[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:a??s}return e})(t),this.chromecastInitializer=new x({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Di(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}>`})))),a=`Player.${String(e)}`,r=`Exception calling ${a} (${s.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:t}),t}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new gi({screenFormatsPriority:[...Ci[_.SCREEN].live,...Ci[_.SCREEN].vod],chromecastFormatsPriority:[...Ci[_.CHROMECAST].live,...Ci[_.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t),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){l(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){return(void 0===t||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t)))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){l(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(a(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(h((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(h((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=S(),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),v()).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(h((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(h((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(h((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(t?.quality),this.info.videoBitrate$.next(t?.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).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(h((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(h((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(h((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekState:t,position$:e})=>o(t.stateChangeEnded$.pipe(h((({to:t})=>t.state===C.None?void 0:(t.position??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(g(!0)),e.providerOutput.seekedEvent$.pipe(g(!1))).pipe(c()).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(h((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(v(),h((()=>S()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(v(),h((()=>S()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(v(),h((()=>S()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const a=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>a.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>a.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)),v()).subscribe((()=>n.next(!1))));let d=0;const u=o(e.providerOutput.isBuffering$,a,n).pipe(h((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=a.getValue()||n.getValue();return t&&!i})),c());this.subscription.add(u.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(r(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(f((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),p.unsubscribe(),t){case!0:p.add(Li({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:m,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).pipe(h((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break;case!1:p.add(Ii({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:m,position$:this.providerContainer.providerOutput.position$}).pipe(h((({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(h((t=>t?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(f((t=>t.length>0)),v()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=_t(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),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(h((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(h((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const t=this.providerContainer?.providerOutput;l(this.providerContainer),l(t),$t={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Et=t})),this.providerContainer.current$.subscribe((({type:t})=>kt('provider',t))),t.duration$.subscribe((t=>kt('duration',t))),t.availableVideoTracks$.pipe(f((t=>!!t.length)),v()).subscribe((t=>kt('tracks',t))),this.events.fatalError$.subscribe(new At('fatalError')),this.events.managedError$.subscribe(new At('managedError')),t.position$.subscribe(new At('position')),t.currentVideoTrack$.pipe(h((t=>t?.quality))).subscribe(new At('quality')),this.info.currentBuffer$.subscribe(new At('buffer')),t.isBuffering$.subscribe(new At('isBuffering'))].forEach((t=>this.subscription.add(t))),kt('codecs',Object.keys(si).filter((t=>si[t])))}}const Bi='@vkontakte/videoplayer-core@2.0.67';export{R as ChromecastState,L as HttpConnectionType,P as PlaybackState,xi as Player,Bi as SDK_VERSION,I as StartStatus,D as VideoFormat,M as VideoQuality};
6
+ import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as a,fromEvent as r,assertNever as n,merge as o,tap as d,map as h,observableFrom as u,filterChanged as c,assertNonNullable as l,debounce as p,timeout as m,filter as f,mapTo as g,now as S,Observable as b,once as v,combine as y,abortable as T,getExponentialDelay as E,interval as w,throttle as $,Logger as k}from'@vkontakte/videoplayer-shared/esnext.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/esnext.esm.js';import A from'lodash/debounce.js';var P,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',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS',t.HLS_LIVE='HLS_LIVE'}(D||(D={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(R||(R={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(_||(_={})),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{connection$=new t(void 0);castState$=new t(_.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(_.NOT_AVAILABLE);subscription=new i;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const e='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${e}`}),t.isDisabled||!e)return;var i;s(window.chrome?.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(i='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const s=document.createElement('script');s.setAttribute('src',i),s.onload=()=>t,s.onerror=()=>e,document.body.appendChild(s)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();a(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();a(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(r(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return n(t.sessionState)}}))).add(o(r(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),h((t=>t.castState))),u([i.getCastState()])).pipe(c(),h(B),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{const n=r===_.CONNECTED,o=s(this.connection$.getValue());if(n&&!o){const s=i.getCurrentSession();l(s);const r=s.getCastDevice(),n=s.getMediaSession()?.media.contentId;(a(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:r}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===_.CONNECTED?s(this.connection$.getValue())?_.CONNECTED:_.AVAILABLE:r)})))}initializeCastApi(){let t,e,i;try{t=cast.framework.CastContext.getInstance(),e=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{t.setOptions({receiverApplicationId:this.params.receiverApplicationId??e,autoJoinPolicy:i}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const B=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _.AVAILABLE;case cast.framework.CastState.CONNECTING:return _.CONNECTING;case cast.framework.CastState.CONNECTED:return _.CONNECTED;default:return n(t)}};var N;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(N||(N={}));var M,O=(t,e=0,i=N.OFFSET_P)=>{switch(i){case N.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case N.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default: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'}(M||(M={}));const V={[M.Q_144P]:{width:256,height:144},[M.Q_240P]:{width:428,height:240},[M.Q_360P]:{width:640,height:360},[M.Q_480P]:{width:856,height:480},[M.Q_720P]:{width:1280,height:720},[M.Q_1080P]:{width:1920,height:1080},[M.Q_1440P]:{width:2560,height:1440},[M.Q_2160P]:{width:3840,height:2160},[M.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===M.INVARIANT;class z{state;transition;transitionStarted$=new e;transitionEnded$=new e;transitionUpdated$=new e;forceChanged$=new e;stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$);constructor(t){this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var Q;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Q||(Q={}));class W{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new z(Q.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case D.MPEG:case D.DASH:case D.DASH_SEP:case D.DASH_ONDEMAND:case D.DASH_WEBM:case D.HLS: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(h((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(h((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(r(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(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),a=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==a&&this.params.output.isBuffering$.next(a),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),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(r(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(r(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$,u(['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();this.videoState.getTransition()?.to!==Q.PAUSED&&t!==Q.PLAYING||(this.videoState.setState(Q.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==Q.PLAYING&&t!==Q.PAUSED||(this.videoState.setState(Q.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY)}handleRemoteStop(){this.videoState.getState()!==Q.STOPPED&&this.videoState.setState(Q.STOPPED)}handleRemoteVolumeChange(t){const e=this.params.output.volume$.getValue(),i={volume:t.volume??e.volume,muted:t.muted??e.muted};i.volume===e.volume&&i.muted==i.muted||this.params.output.volume$.next(i)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){const e=this.params.source;let i,a,r;switch(t){case D.MPEG:{const s=e[t];l(s);const n=Object.keys(s).sort(((t,e)=>t===e?0:t===M.INVARIANT?1:e===M.INVARIANT?-1:F(t,e)?1:-1))[0];l(n);const o=s[n];l(o),i=o,a='video/mp4',r=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS:case D.HLS_ONDEMAND:{const s=e[t];l(s),i=s.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case D.DASH_SEP:case D.DASH_ONDEMAND:case D.DASH_WEBM:{const s=e[t];l(s),i=s.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS_LIVE:{const s=e[t];l(s),i=O(s.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}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}case D.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return n(t)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);o.contentUrl=i,o.streamType=r,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:h}=this.params.meta;return s(d)&&(o.metadata.title=d),s(h)&&(o.metadata.subtitle=h),o}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)}`})}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)if(s?.to===P.PAUSED||a.state!==C.Requested||t===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(a.position)}else t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.stop())}}class j{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 j{constructor(){super(),this.listeners||j.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 X{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 K(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&&(X.prototype[Symbol.toStringTag]='AbortController',J.prototype[Symbol.toStringTag]='AbortSignal');const Z=K({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:a=!1}=t;if(!K({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const a=new i(t,e);return s&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),a},r.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=r&&r.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const a=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,n(t,e)])}return n(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=Z?tt.fetch:window.fetch;Z?tt.Request:window.Request;const it=Z?X:window.AbortController,st=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class at{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){const{url:e}=t.request,i=this.dashJsRequestQueue.get(e)??[];i.push(t),this.dashJsRequestQueue.set(e,i)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=st(s.request);if(a>=i.from&&r<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){if(t){const{request:e}=t,i=(this.dashJsRequestQueue.get(e.url)??[]).includes(t),s=this.activeRequests.get(e.url);i&&s&&s.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(st),s=i[0][0];let a=i[0][1];for(let t=1;t<i.length&&a<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===s?Math.max(a,s+this.params.minInitSize):Math.max(a,s+this.params.minDataSize);const r=new URL(t,location.href);r.searchParams.append('bytes',`${s}-${a}`);const n=r.toString(),o=new it,d=o.signal,h={url:t,from:s,to:a,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(h)));const u=t=>{throw this.params.onError?.({id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return et(n,{signal:d}).then((t=>{if(h.response=t,!t.ok||!t.body)return void this.onBigRequestError(h);const[e,i]=t.body.tee();this.params.onDownloadStream?.(i);const r=e.getReader(),n=parseInt(t.headers.get('Content-Length')??'',10)||a-s+1;h.data=new ArrayBuffer(n);const o=new Uint8Array(h.data),d=async({done:t,value:e})=>{t?this.onBigRequestProgress(h):e&&(o.set(e,h.loaded),h.loaded+=e.byteLength,this.onBigRequestProgress(h),await(r?.read().then(d,at.suppressStreamErrors).catch(u)))};r?.read().then(d,at.suppressStreamErrors).catch(u)}),at.suppressAbort).catch((t=>this.onBigRequestError(h,t))),h}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a,response:r}){if(!this.activeRequests.has(t)||!a)return;const n=this.dashJsRequestQueue.get(t)??[];for(const o of n){const{request:n}=o,[d,h]=st(n),u=d>=e&&h<=e+s,c=e>=d&&e+s<h,l=a.slice(d-e,Math.min(h-e+1,s));if((u||c)&&(n.requestStartDate=n.requestStartDate??new Date,n.firstByteDate=n.firstByteDate??new Date,n.bytesLoaded=l.byteLength,n.bytesTotal=i-e),u){n.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(this.dashJsRequestQueue.get(t)??[]).filter((t=>t!==o))),o.success?.(l,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';this.dashMetrics?.addHttpRequest(n,t,r?.status??200,e,[])}else c&&o.progress?.({loaded:s,total:i-e,lengthComputable:!0,stream:!0})}}onBigRequestError({url:t,from:e,to:i},s){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const a=this.dashJsRequestQueue.get(t)??[];for(const t of a){const[a,r]=st(t.request);(a>=e&&a<i||r>e&&r<=i)&&t?.error?.(t.request,String(s))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){if(!this.activeRequests.has(t))return;const s=this.dashJsRequestQueue.get(t)??[];for(const t of s){const[s,a]=st(t.request);(s>=e&&s<i||a>e&&a<=i)&&t?.abort?.(t.request)}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class rt{baseLoader;config;bigRequest;constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(rt.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;rt.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const nt=(t,e)=>{const i=new at(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new rt(a,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&&e?.()})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&e?.()}}}),!0)},dt=i=>{const a=new t(1/0),r=new e,n=new t(void 0),o=new t(void 0);let d=NaN,h=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{const e=Object.fromEntries(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in e||'x-playback-duration-millis'in e){const e=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),i=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*e??NaN;s(i)&&!isNaN(i)&&a.next(i)}const i=e['x-delivery-type']??L.HTTP1,r={1:!0,0:!1}[e['x-reused']]??void 0;n.next(i),o.next(r)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!h&&(h=!0,r.next(Date.now()-d)),i(...t)},d=Date.now(),h=!1}return e(t)}}}),!0),{playbackDuration$:a,ping$:r,connectionReused$:o,connectionType$:n}},ht=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},ut=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 ct=(t,e,s,{equal:r=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),h=e(),u=a(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();r(e,i)&&t.setState(e)}),o)),r(h,d)||(s(d),u&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),u&&t.setState(e.to)}),o)),c},lt=(t,e,i)=>ct(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),pt=(t,e,i,a)=>ct(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||t?.muted===e?.muted&&t?.volume===e?.volume,changed$:i,onError:a}),mt=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class ft{available$=new e;current$=new t(void 0);error$=new e;video;cueSettings;subscription=new i;externalTracks=new Map;connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const a=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(ct(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(h((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(ct(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:a})),this.subscription.add(ct(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(r(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(r(t,'addtrack'),r(t,'removetrack'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(o(r(t,'change'),u(['init'])).pipe(h((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),h((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>this.applyCueSettings(t.target?.activeCues??null);this.subscription.add(r(t,'addtrack').subscribe((t=>{t.track?.addEventListener('cuechange',e);const i=t=>{const e=t.target?.cues??null;e&&e.length&&(this.applyCueSettings(t.target?.cues??null),t.target?.removeEventListener('cuechange',i))};t.track?.addEventListener('cuechange',i)}))),this.subscription.add(r(t,'removetrack').subscribe((t=>{t.track?.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(ft.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&mt(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){l(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){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var gt=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class St{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}class bt{_buffer=[];_source;constructor(t){this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:a})=>{const r=s>=t&&s<e,n=a>=t&&a<e;r&&n||(r?i(e,a):n?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var vt=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(s=n,a=o,!i)return{from:s,to:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{from:s,to:a}};const yt=t=>{const i=e=>r(t,e).pipe(g(void 0)),a=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>r(t,e)))).pipe(h((()=>t.readyState<3)),c()),n=o(r(t,'progress'),r(t,'timeupdate')).pipe(h((()=>vt(t.buffered,t.currentTime)))),d=r(t,'volumechange').pipe(p(0),h((()=>({muted:t.muted,volume:t.volume})))),u=r(t,'error').pipe(h((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),l=r(t,'timeupdate').pipe(h((()=>t.currentTime))),m=new e;let S;return l.subscribe((e=>{t.loop&&s(S)&&s(e)&&S>=t.duration-.3&&e<=.3&&m.next(S),S=e})),{playing$:i('playing'),pause$:i('pause').pipe(f((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:m,error$:u,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:r(t,'durationchange').pipe(h((()=>t.duration))),isBuffering$:a,currentBuffer$:n,volumeState$:d}},Tt=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};let Et=!1,wt={};const $t=t=>{t(wt)},kt=(t,e)=>{Et&&(wt.meta=wt.meta??{},wt.meta[t]=e)};class At{name;constructor(t){this.name=t}next(t){if(!Et)return;wt.series=wt.series??{};const e=wt.series[this.name]??[];e.push([Date.now(),t]),wt.series[this.name]=e}}const Pt=new At('best_bitrate');class Dt{last;history={};recordSelection(t){this.history[t.id]=S()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const Rt=(t,{container:e,throughput:i,tuning:r,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:h,current:u,history:c})=>{const l=r.usePixelRatio?window.devicePixelRatio??1:1,p=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*r.containerSizeFactor,height:e.height*l*r.containerSizeFactor},m=p&&G(p),f=r.considerPlaybackRate&&s(h)?h:1,g=t.filter((t=>!Y(t.quality))).sort(((t,e)=>q(t.quality,e.quality)?-1:1)),b=g.at(-1)?.quality,v=g.at(0)?.quality,y=a(n)||s(n.min)&&s(n.max)&&F(n.max,n.min)||s(n.min)&&v&&q(n.min,v)||s(n.max)&&b&&F(n.max,b),T=f*(E=d??.5,w=r.bitrateFactorAtEmptyBuffer,$=r.bitrateFactorAtFullBuffer,(w-$)*Math.pow(2,-10*E)+$);var E,w,$;const k=g.filter((t=>{const e=!m||F(t.quality,m),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*T,c=r.lazyQualitySwitch&&s(r.minBufferToSwitchUp)&&u&&!Y(u.quality)&&(d??0)<r.minBufferToSwitchUp&&q(t.quality,u.quality),l=y||(a(n.max)||(p=t.quality,f=n.max,V[p].height<=V[f].height))&&(a(n.min)||((t,e)=>V[t].height>=V[e].height)(t.quality,n.min));var p,f;return e&&h&&!c&&l}))[0];k&&k.bitrate&&Pt.next(k.bitrate);const A=k??g[Math.ceil((g.length-1)/2)]??t[0],P=A&&c&&c.history[A.id]&&S()-c.history[A.id]<=r.trackCooldown&&(!c.last||A.id!==c.last.id);if(A?.id&&c&&!P&&c.recordSelection(A),P&&c?.last){const t=c.last;return c?.recordSwitch(t),t}return c?.recordSwitch(A),A};var _t=t=>new URL(t).hostname;const It=(t,e=300)=>new b((i=>{const{width:a,height:r}=t.getBoundingClientRect();if(i.next({width:a,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let a,r;e.contentBoxSize&&e.contentBoxSize[0]?(r=e.contentBoxSize[0].blockSize,a=e.contentBoxSize[0].inlineSize):e.contentRect&&(a=e.contentRect.width,r=e.contentRect.height),s(a)&&s(r)&&i.next({width:a,height:r})}),e));return n.observe(t),()=>n.disconnect()})),Lt={};var Ct;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ct||(Ct={}));const xt=(t,e)=>new b((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Bt{subscription=new i;videoState=new z(Ct.DOWNLOADING_LIB);video;player;params;textTracksManager=new ft;videoTracks=[];frameRatesByFrameHeight={};isLive$=new t(void 0);maxSeekBackTime$=new t(1/0);availableFrom$=new t(void 0);elementSize$=new t(void 0);liveOffset=new St;destroyBigRequest;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(_t(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${e?.toString?.()}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Lt.MediaPlayer=e.MediaPlayer,Lt.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Lt.MediaPlayer,'dashjs not loaded'),l(Lt.Debug,'dashjs not loaded'),this.player=Lt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter((t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Tt(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&&ut(this.player),ot(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:ht})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Ct.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(It(this.video),this.elementSize$),r(xt(this.player,'error').pipe(h((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),r(xt(this.player,'playbackError').pipe(h((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=xt(this.player,'qualityChangeRendered').pipe(f((({mediaType:t})=>'video'===t)),h((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));n.pipe(f(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(f((({to:t})=>t===Ct.STREAM_INITIALIZED)),v()).subscribe((()=>{this.subscription.add(ct(e.videoTrack,(()=>{const t=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track?.id}),(t=>{if(a(t))return;const e=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;e&&this.player.setQualityFor('video',e.qualityIndex)}),{changed$:n.pipe(h((t=>t?.id))),onError:i}))}),i)),this.subscription.add(ct(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),r(xt(this.player,'bufferStateChanged').pipe(f((({mediaType:t})=>'video'===t)),h((({state:t})=>'bufferStalled'===t))),t.isBuffering$),r(xt(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{const s=this.player.getDashMetrics(),a=s.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),r=s.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type')??L.HTTP1,n={1:!0,0:!1}[a]??void 0;this.params.output.httpConnectionType$.next(r),this.params.output.httpConnectionReused$.next(n),t.hostname$.next(_t(i))})),r(xt(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=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===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(Ct.STREAM_INITIALIZED),this.videoState.startTransitionTo(Ct.READY)})),r(xt(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)})),r(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=Rt(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));s?.bitrateInfo&&this.player.setQualityFor('video',s?.bitrateInfo.qualityIndex,!1)})),r(y({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(f(s))}).pipe(f((({isLive:t})=>t)),h((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const d=xt(this.player,'playbackTimeUpdated').pipe(h((({time:t})=>t??0)));r(y({availableFrom:this.availableFrom$.pipe(f(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(d.pipe(f((()=>!1===this.isLive$.getValue()))),t.position$),r(xt(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),r(xt(this.player,'playbackEnded'),t.endedEvent$),r(xt(this.player,'playbackProgress').pipe(h((()=>vt(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),r(xt(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Ct.PLAYING),U(e.playbackState,P.PLAYING)})),r(xt(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Ct.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(xt(this.player,'playbackPaused'),(()=>{this.videoState.setState(Ct.PAUSED),U(e.playbackState,P.PAUSED)})),r(xt(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===Ct.READY&&this.videoState.setState(Ct.READY)})),r(this.isLive$,t.isLive$),r(It(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,u(['init'])).pipe(p(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l,connectionType$:m,connectionReused$:S}=dt(this.player);r(m,this.params.output.httpConnectionType$),r(S,this.params.output.httpConnectionReused$),r(c,this.maxSeekBackTime$),r(l.pipe(v()),t.firstBytesEvent$),r(xt(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(y({isLive:this.isLive$,isShort:t.duration$.pipe(h((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),r(d.pipe(f((t=>t>this.params.tuning.insufficientBufferRuleMargin)),v()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(xt(this.player,'manifestLoaded').pipe(v()).subscribe((()=>{this.subscription.add(xt(this.player,'playbackPlaying').pipe(v(),g(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(lt(this.video,e.isLooped,i));const{volumeState$:b,looped$:T}=yt(this.video);this.subscription.add(pt(this.video,e.volume,b,i)),this.subscription.add(b.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(Ct.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Ct.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=O(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,N.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Ct.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Ct.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==Ct.DOWNLOADING_LIB&&t!==Ct.STREAM_INITIALIZED)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&t!==Ct.STOPPED&&e!==P.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case Ct.STOPPED:break;case Ct.PLAYING:case Ct.PAUSED:case Ct.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Ct.PLAYING:break;case Ct.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Ct.READY:this.play();break;case Ct.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Ct.PLAYING:this.pause(),this.liveOffset.pause();break;case Ct.PAUSED:break;case Ct.READY:this.videoState.setState(Ct.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case Ct.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Nt=t=>{switch(t){case'mobile':return M.Q_144P;case'lowest':return M.Q_240P;case'low':return M.Q_360P;case'sd':case'medium':return M.Q_480P;case'hd':case'high':return M.Q_720P;case'fullhd':case'full':return M.Q_1080P;case'quadhd':case'quad':return M.Q_1440P;case'ultrahd':case'ultra':return M.Q_2160P}},Mt=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function Ot(){return S()}function Ut(t){return Ot()-t}function Vt(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function qt(t,e,i,a){const r=window.XMLHttpRequest;let n,o,d,h,u,c=!1,p=0,m=!1,f='arraybuffer',g=7e3,S=2e3,b=()=>{if(c)return;l(h);const t=Ut(h);let e;if(t<S)return e=S-t,void setTimeout(b,e);S*=2,S>g&&(S=g),o&&o.abort(),o=new r,y()};const v=()=>{if(!c){if(--p>=0)return b(),void(a&&a());c=!0,u&&u(),i&&i()}},y=()=>{h=Ot(),o=new r,o.open('get',t);let i,s=0,a=0;const p=()=>(l(h),Math.max(h,Math.max(i||0,a||0)));if(n&&o.addEventListener('progress',(t=>{const e=Ot();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(c)return;l(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)}u&&u(),o&&e(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),m){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(a=Ot(),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)&&(S=t),s(e)&&(g=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(u=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,u&&u()}};return T}class Ft{intervals=[];currentRate=0;logger;constructor(t){this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const n=t.bytes*a/r;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:'warn'}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}}class Ht{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(t,e,i,s,a){this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=Ot(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=qt(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Ot()-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=Ot()}_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=Ot();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class Gt{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(t){this.params=t,this.chunkRateEstimator=new Ft(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Vt(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=Vt(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=>{this.destroyed||(e(`Video element error: ${t.error?.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,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ht(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:r}=this.params;let n=!1,o=null,d=null,h=null,u=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{h&&h.abort(),h=qt(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{h=null})).send()},f=(t,e,i)=>{l(this.filesFetcher),d?.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},g=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},S=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void g(1);const i=Ot()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const a=this.bufferStates[e];t=Math.min(t,a.buf),a.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,g(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else g(1)},v=t=>{let i;const a=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,h=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=e;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=i.dur.length-1;for(;r>=0&&(a-=i.dur[r],!(a<=0));--r);t=Math.min(r,i.dur.length-1-s),t=Math.max(t,0)}return h(t,!0)},m=(t,e,i)=>{u&&u.abort(),u=qt(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&S(d);let u=0;for(let t=0;t<i.dur.length;++t)u+=i.dur[t];u>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),r({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=a();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return h(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=a(),r=t?t.chunkIdx+1:0,n=r-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return h(r-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),h&&h.abort(),u&&u.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let r,d,h,c,g,S,T,E=v(t.jidxUrl),w=0;const $=()=>{g&&(clearTimeout(g),g=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Ot(),s=Math.min(1e4,e-i);w=i;const a=()=>{u||p()&&E.seek((()=>{p()&&(w=Ot(),k(),$())}))};s>0?g=window.setTimeout((()=>{this.paused?$():a()}),s):a()},k=()=>{let e;for(;e=E.nextChunk(c);)c=e,_(e);const i=E.nextChunk(h);if(i){if(h&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));R(i)}else $()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let a,r,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=Ot(),h=i.currentTime;!this.paused&&i.buffered.length>1&&S===h&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),S!==h&&(S=h,T=d);const u=this._getBufferSizeSec();if(u>30)s(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(a=this.sourceBuffer.buffered.start(0),r=h,r-a>4&&this.sourceBuffer.remove(a,r-3)),o(1e3)}}},P=()=>{d&&r&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),A(d,(function(){d=null,k()})))},D=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),R=t=>{p()&&f(D(t),((e,i)=>{if(p()){if(i/=1e3,d=e,h=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}P()}}),(()=>this._handleNetworkError()))},_=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{r=!0,P()})))};n=!0,E.seek((t=>{p()&&(w=Ot(),t?(c=t,!a(e)||t.startTS>e?R(t):(h=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),s(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Ot();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(n&&t>a&&Ut(r)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=Ot();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=qt(this.urlResolver.resolve(t,!0),e,i,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;Mt(e).then((e=>{e||t?.()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return t?.length?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var Yt;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Yt||(Yt={}));const zt=[Yt.PAUSED,Yt.PLAYING,Yt.READY],Qt=[Yt.PAUSED,Yt.PLAYING,Yt.READY];class Wt{subscription=new i;video;videoState=new z(Yt.STOPPED);dash;representations$=new t([]);textTracksManager=new ft;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new St;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const e=e=>{t.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:e})};o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(_t(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=yt(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Yt.READY&&this.videoState.setState(Yt.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(Yt.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Yt.PLAYING)}),e)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),h((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(y({zeroTime:this.zeroTime$.pipe(f(s)),position:i.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(lt(this.video,this.params.desiredState.isLooped,e)).add(pt(this.video,this.params.desiredState.volume,i.volumeState$,e)).add(i.volumeState$.subscribe(this.params.output.volume$,e)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&V[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Yt.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case Yt.MANIFEST_READY:case Yt.READY:break;case Yt.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case Yt.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return n(t.to)}}),e)).add(o(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekState.stateChangeEnded$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(p(0)).subscribe(this.syncPlayback,e))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Gt({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){const t=this.representations$.getValue(),e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s(e)?e:Rt(t.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.id,r=t.find((({track:t})=>t.id===a))?.representation;l(r,'Representations missing'),this.dash.startPlay(r,i),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(i)}setVideoTrack(t){const e=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;l(e,`No such representation ${t}`),this.dash.switchByName(e.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(O(this.params.source.url,i))}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,i=[];for(const t of e){const e=t.name??t.index.toString(10),s=Nt(t.name)??G(t.video),a=t.bitrate/1e3,r={...t.video};if(!s)continue;const n={id:e,quality:s,bitrate:a,size:r};i.push({track:n,representation:t})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map((({track:t})=>t))),this.videoState.getTransition()?.to===Yt.MANIFEST_READY&&this.videoState.setState(Yt.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=this.representations$.getValue().find((({representation:t})=>t===e))?.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e){if(Qt.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;s(t)&&this.setVideoTrack(t);const e=this.params.desiredState.autoVideoTrackSwitching.getTransition();e&&this.setAutoQuality(e.to)}if(a?.to!==P.PAUSED&&r.state===C.Requested&&zt.includes(t))this.seek(r.position-this.liveOffset.getTotalPausedTime());else switch(t){case Yt.STOPPED:return this.videoState.startTransitionTo(Yt.MANIFEST_READY),void this.dash.attachSource(O(this.params.source.url));case Yt.MANIFEST_READY:this.videoState.startTransitionTo(Yt.READY),this.prepare();break;case Yt.READY:return void(i===P.PAUSED?this.videoState.setState(Yt.PAUSED):i===P.PLAYING&&(this.videoState.startTransitionTo(Yt.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Yt.PAUSED)}))));case Yt.PLAYING:return void(i===P.PAUSED&&(this.videoState.startTransitionTo(Yt.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Yt.PAUSED:return void(i===P.PLAYING&&(this.videoState.startTransitionTo(Yt.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(Yt.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return n(t)}}}else t!==Yt.STOPPED&&(this.videoState.startTransitionTo(Yt.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Yt.STOPPED))}}var jt=t=>{const e=t.get('X-Delivery-Type'),i=t.get('X-Reused');return{type:null===e?L.HTTP1:e??void 0,reused:null===i?void 0:{1:!0,0:!1}[i]??void 0}},Jt=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)};class Xt{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(t,e=[],i,s,a,r){this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(l(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Kt{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(t){this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),e?.()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,c=0;const l=t=>{s(Kt._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=ht(p)),this._lastXhr=new Xt(p,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),a?.()}),(t=>{if(t.length-o>n&&l(t),0===u)return void(u=Date.now());c=t.length-h;const e=Date.now()-u;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,h=t.length,u=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),t?.()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Kt._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class Zt{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(t){this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=t.onDashCallback??(()=>{}),this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===i?.[1]?-1:1;e(i?.[2],s),e(i?.[3],s),e(i?.[4],s),e(i?.[5],s);return 3600*e(i?.[6],s)+60*e(i?.[7],s)+e(i?.[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=ht(i)),new Xt(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{const s=t.getElementsByTagName('SegmentBase')[0],o=s&&a(s,'indexRange').split('-'),d=s&&s.getElementsByTagName('Initialization')[0],h=d&&a(d,'range').split('-');if(!h||!o){const e=t.parentElement;if('text'===e?.getAttribute('contentType')){const s=t.getAttribute('id')??void 0,a=(i?i+'/':'')+t.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=e.getAttribute('lang')??void 0;a&&n.push({id:s,url:a,language:r})}return}const u=Number(t.attributes.getNamedItem('bandwidth')?.value),c=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=t.attributes.getNamedItem('frameRate')?.value??void 0;l=p?Tt(p):void 0,r.push({width:Number(t.attributes.getNamedItem('width')?.value),height:Number(t.attributes.getNamedItem('height')?.value),bandwidth:u,baseURL:c,failoverHosts:e,indexFrom:Number(o[0]),indexTo:Number(o[1]),initFrom:Number(h[0]),initTo:Number(h[1]),codecs:t.attributes.getNamedItem('codecs')?.value??void 0,mimeType:t.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*u/8,bufferLength:.1,name:t.attributes.getNamedItem('okQuality')?.value??void 0,id:t.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let n=a.getUint32(s,!1),o=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&a.getUint32(s,!1)),i=n+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/r,toTime:i/r,fromOffset:o,toOffset:e-1}),o=e,n=i}const h=t.refs[t.refs.length-1];h.toTime-h.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let r;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.to-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.to&&(a=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new Kt({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const a=this._findRef(e);if(a){if(i){this._isLastRef(a)&&e>=a.toTime&&(e=a.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:a.fromTime}this._appendVector[String(a.fromTime)]=t,this._stream.load(t,a.fromOffset,a.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const a=.1;if(s.toTime<i.to+a){const e=this._findRef(s.toTime);e&&e.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!a(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){const e=this._currentRepresentation?.refs;if(!e)return;if(Array.isArray(e)&&0===e.length)return void this._params.onError('emptyrefs','Empty refs');let i;for(let s=0;s<e.length;s++){const a=e[s];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!i||a.fromTime<i.fromTime)&&(i=a)}if(!i){const i=e[e.length-1];if(t>i.toTime)return i}return i}_isLastRef(t){const e=this._currentRepresentation?.refs;if(!e)return!1;const i=e[e.length-1];return t.fromTime===i.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var te;!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'}(te||(te={}));const ee=[te.PAUSED,te.PLAYING];class ie{videoState=new z(te.STOPPED);subscription=new i;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new ft;elementSize$=new t(void 0);dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(h((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(h((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(_t(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new bt(this.video),this.dash=new Zt({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=yt(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,i));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.looped$,t.loopedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.playing$,t.firstFrameEvent$),l(d.canplay$,t.canplay$),this.subscription.add(d.seeking$.subscribe((()=>{a(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===te.PLAYING||this.videoState.getState()===te.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(lt(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(It(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(te.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(te.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(te.METADATA_LOADED)}),i)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(h((({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$,r(this.video,'progress')).pipe(h((()=>{const t=this.currentRepresentation$.getValue(),e=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.videoTrack.getState(),r=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),o=this.elementSize$.getValue(),d=n();let h;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&s(a))h=a;else{const i=Jt(this.video.buffered,1e3*this.video.currentTime),s=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(i/s,1);h=Rt(e.map((({track:t})=>t)),{container:o,throughput:r,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:e.find((({representation:e})=>e===t))?.track})?.id}return s(h)?e.find((({track:t})=>t.id===h))?.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(y({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(f((t=>t.to===te.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(f(s))}).pipe(v()).subscribe((()=>this.videoState.setState(te.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(f(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=Jt(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(_t(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=jt(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(v(),g(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$,u(['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)}}handleManifestReady=t=>{const e=[];for(const i of t){const t=i.name??i.id??i.height.toString(10),s=(i.name&&Nt(i.name))??G(i),a=i.bandwidth/1e3,r={width:i.width,height:i.height},n=i.fps;if(!s)continue;const o={id:t,quality:s,bitrate:a,size:r,fps:n};e.push({track:o,representation:i})}this.representations$.next(e),this.params.output.availableVideoTracks$.next(e.map((({track:t})=>t))),this.videoState.setState(te.MANIFEST_LOADED)};handleRepresentationPlay=t=>{const e=this.representations$.getValue().find((({representation:e})=>e===t))?.track;if(e){this.params.output.currentVideoTrack$.next(e);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(e.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t};seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(te.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)switch(s?.to!==P.PAUSED&&a.state===C.Requested&&ee.includes(t)&&this.seek(a.position,a.forcePrecise),t){case te.STOPPED:return this.videoState.startTransitionTo(te.MANIFEST_LOADED),void this.prepare();case te.MANIFEST_LOADED:return void this.videoState.startTransitionTo(te.INITIAL_REPRESENTATION_SELECTED);case te.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(te.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case te.METADATA_LOADED:return this.videoState.startTransitionTo(te.READY),void this.dash.updateRefsForCurrentTime();case te.READY:return void(i===P.PAUSED?(this.videoState.setState(te.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()));case te.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):s?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case te.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):s?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))}}var se,ae,re,ne,oe;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(se||(se={})),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'}(ae||(ae={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(re||(re={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(ne||(ne={})),function(t){t.MP4='mp4',t.WEBM='webm'}(oe||(oe={}));var de=(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 he='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 ue=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};let ce=!1;try{ce=ue()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??'',10)<16}catch(t){console.error(t)}class le{bufferFull$=new e;error$=new e;buffer;queue=[];currentTask=null;destroyed=!1;constructor(t){this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const a={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(a),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=ce&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}completeTask=()=>{try{if(this.currentTask){const t=this.currentTask.signal?.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown:t})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(t.signal?.aborted)return t.callback(!1),void this.pull();this.currentTask=t;const{operation:e}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===e&&this.bufferFull$.next(this.currentTask.data.byteLength),t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===e||this.error$.next({id:`BufferTaskQueue:${e}`,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 pe;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(pe||(pe={}));class me{throughputEstimator;requestQuic;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new it;subscription=new i;constructor({throughputEstimator:t,requestQuic:e}){this.throughputEstimator=t,this.requestQuic=e}onHeadersReceived(t){const{type:e,reused:i}=jt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest=T(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=ht(e));const i=yield et(e,{signal:this.abortAllController.signal}).catch(fe);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=T(this.abortAllController.signal,async function*(t,{rangeMethod:e=pe.HEADER,range:i,onProgress:s,priority:a='auto',signal:d,measureThroughput:h=!0}={}){let u=t;const c=new Headers;if(i)switch(e){case pe.HEADER:c.append('Range',`${i.from}-${i.to}`);break;case pe.PARAM:{const t=new URL(u,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),u=t.toString();break}default:n(e)}this.requestQuic&&(u=ht(u));let l=this.abortAllController.signal;if(d){const t=new it;if(this.subscription.add(o(r(this.abortAllController.signal,'abort'),r(d,'abort')).subscribe((()=>{try{t.abort()}catch(t){fe(t)}}))),this.abortAllController.signal.aborted||d.aborted)try{t.abort()}catch(t){fe(t)}l=t.signal}const p=S(),m=yield et(u,{priority:a,headers:c,signal:l}).catch(fe),f=S();if(this.throughputEstimator?.addRawRtt(f-p),!m)return null;if(!m.ok||!m.body)return Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));this.onHeadersReceived(m.headers);const g=parseInt(m.headers.get('Content-Length')??'',10)||i&&i.to-i.from+1||NaN;if(!g){const t=yield m.arrayBuffer();return this.throughputEstimator?.addRawSpeed(t.byteLength,S()-f),s?.(new DataView(t),t.byteLength),t}if(!s&&!h)return m.arrayBuffer();const[b,v]=m.body.tee(),y=b.getReader();h&&this.throughputEstimator?.trackStream(v);let E=0;const w=new ArrayBuffer(g),$=new Uint8Array(w),k=new DataView(w);let A=!1;const P=t=>{A=!0,fe(t)},D=T(l,async function*({done:t,value:e}){0===E&&this.lastRequestFirstBytes$.next(S()-p),l.aborted||(t?s?.(k,E):e&&($.set(e,E),E+=e.byteLength,s?.(k,E),yield y?.read().then(D,P)))}.bind(this));return yield y?.read().then(D,P),A?null:w}.bind(this));async fetchRepresentation(t,e,i='auto'){const{type:s}=t;switch(s){case re.BYTE_RANGE:return await this.fetchByteRangeRepresentation(t,e,i)??null;case re.TEMPLATE:return await this.fetchTemplateRepresentation(t,i)??null;default:n(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=T(this.abortAllController.signal,async function*(t,e,i){if(t.type!==re.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,n,o=s,d=a,h=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,h=a+1===r,h&&(o=Math.min(r,s),d=Math.max(n,a))),o=Math.min(o,0);const u=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!u)return null;const c=new DataView(u,s-o,a-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(h&&void 0!==r&&void 0!==n)p=new DataView(u,r-o,n-r+1);else{const s=e.getIndexRange(l);if(s){const e=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,l);return{dataView:new DataView(u),segments:m}}.bind(this));fetchTemplateRepresentation=T(this.abortAllController.signal,async function*(t,e){if(t.type!==re.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:ne.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this))}const fe=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},ge=new TextDecoder('ascii'),Se=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=ge.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},be={validateData:t=>'ftyp'===ge.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Se(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),d=4294967295&a();let h=n/r*1e3,u=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=a(),e=t>>>31,s=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;i.push({status:ne.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=Se(a);if(s||='mdat'===i.id,!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var ve,ye;!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'}(ve||(ve={})),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'}(ye||(ye={}));const Te={[ve.EBML]:{type:ye.Master},[ve.EBMLVersion]:{type:ye.UnsignedInteger},[ve.EBMLReadVersion]:{type:ye.UnsignedInteger},[ve.EBMLMaxIDLength]:{type:ye.UnsignedInteger},[ve.EBMLMaxSizeLength]:{type:ye.UnsignedInteger},[ve.DocType]:{type:ye.String},[ve.DocTypeVersion]:{type:ye.UnsignedInteger},[ve.DocTypeReadVersion]:{type:ye.UnsignedInteger},[ve.Void]:{type:ye.Binary},[ve.Segment]:{type:ye.Master},[ve.SeekHead]:{type:ye.Master},[ve.Seek]:{type:ye.Master},[ve.SeekID]:{type:ye.Binary},[ve.SeekPosition]:{type:ye.UnsignedInteger},[ve.Info]:{type:ye.Master},[ve.TimestampScale]:{type:ye.UnsignedInteger},[ve.Duration]:{type:ye.Float},[ve.Tracks]:{type:ye.Master},[ve.Chapters]:{type:ye.Master},[ve.Cluster]:{type:ye.Master},[ve.Timestamp]:{type:ye.UnsignedInteger},[ve.SilentTracks]:{type:ye.Master},[ve.SilentTrackNumber]:{type:ye.UnsignedInteger},[ve.Position]:{type:ye.UnsignedInteger},[ve.PrevSize]:{type:ye.UnsignedInteger},[ve.SimpleBlock]:{type:ye.Binary},[ve.BlockGroup]:{type:ye.Master},[ve.EncryptedBlock]:{type:ye.Binary},[ve.Attachments]:{type:ye.Master},[ve.Tags]:{type:ye.Master},[ve.Cues]:{type:ye.Master},[ve.CuePoint]:{type:ye.Master},[ve.CueTime]:{type:ye.UnsignedInteger},[ve.CueTrackPositions]:{type:ye.Master},[ve.CueTrack]:{type:ye.UnsignedInteger},[ve.CueClusterPosition]:{type:ye.UnsignedInteger},[ve.CueRelativePosition]:{type:ye.UnsignedInteger},[ve.CueDuration]:{type:ye.UnsignedInteger},[ve.CueBlockNumber]:{type:ye.UnsignedInteger},[ve.CueCodecState]:{type:ye.UnsignedInteger},[ve.CueReference]:{type:ye.Master},[ve.CueRefTime]:{type:ye.UnsignedInteger}},Ee=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=we(t,i),a=s in Te,r=a?Te[s].type:ye.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),h=((n&255>>o)<<8*(o-1))+we(d),u=i+o;let c;return c=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:u,tagSize:u+h,value:c,valueSize:h}},we=(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},$e=(t,e)=>{switch(e){case ye.SignedInteger:return t.getInt8(0);case ye.UnsignedInteger:return we(t);case ye.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case ye.String:return new TextDecoder('ascii').decode(t);case ye.UTF8:return new TextDecoder('utf-8').decode(t);case ye.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case ye.Master:case ye.Binary:return t;default:n(e)}},ke=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=Ee(s);if(!e(a))return;a.type===ye.Master&&ke(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},Ae=[ve.Info,ve.SeekHead,ve.Tracks,ve.Chapters,ve.Cluster,ve.Cues,ve.Attachments,ve.Tags],Pe=[ve.Timestamp,ve.SilentTracks,ve.SilentTrackNumber,ve.Position,ve.PrevSize,ve.SimpleBlock,ve.BlockGroup,ve.EncryptedBlock],De={validateData:t=>{if(t.getUint32(0)!==ve.EBML)return!1;let e,i,s;const a=Ee(t);return ke(a.value,(({tag:t,type:a,value:r})=>(t===ve.EBMLReadVersion?e=$e(r,a):t===ve.DocType?i=$e(r,a):t===ve.DocTypeReadVersion&&(s=$e(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,a,r,n,o=!1,d=!1,h=!1;return ke(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===ve.SeekID){const t=$e(c,u);n=we(t)}else t!==ve.SeekPosition&&(n=void 0);return t===ve.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===ve.Info?o=!0:t===ve.SeekHead?d=!0:t===ve.TimestampScale?s=$e(c,u):t===ve.Duration?a=$e(c,u):t===ve.SeekPosition&&n===ve.Cues?r=$e(c,u):o&&d&&Ae.includes(t)&&(h=!0),!h})),l(e,'Failed to parse webm Segment start'),l(i,'Failed to parse webm Segment end'),l(a,'Failed to parse webm Segment duration'),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:r}},getIndexRange:t=>{if(a(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,a=!1;const r=t=>s(t.time)&&s(t.position),n=[];let o;return ke(t,(({tag:t,type:e,value:s})=>{switch(t){case ve.Cues:i=!0;break;case ve.CuePoint:o&&r(o)&&n.push(o),o={};break;case ve.CueTime:o&&(o.time=$e(s,e));break;case ve.CueTrackPositions:break;case ve.CueClusterPosition:o&&(o.position=$e(s,e));break;default:i&&Ae.includes(t)&&(a=!0)}return!(i&&a)})),o&&r(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:a}=t,r=n[i+1];return{status:ne.NONE,time:{from:s,to:r?r.time:e.segmentDuration},byte:{from:e.segmentStart+a,to:r?e.segmentStart+r.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{ke(t,(s=>s.tag===ve.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Pe.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||=[ve.SimpleBlock,ve.BlockGroup,ve.EncryptedBlock].includes(s.tag)),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class Re{onLastSegment$=new t(!1);fullyBuffered$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;gaps=[];subscription=new i;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new it;destroyAbortController=new it;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;constructor(t,e,i,s,{fetcher:a,tuning:r,getCurrentPosition:o}){switch(this.fetcher=a,this.tuning=r,this.forwardBufferTarget=r.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case oe.MP4:this.containerParser=be;break;case oe.WEBM:this.containerParser=De;break;default:n(i)}this.initData=new Map(s.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(s.map((t=>[t.id,t]))),this.kind=t,this.mediaSource=e,this.sourceBuffer=null}startWith=T(this.destroyAbortController.signal,async function*(t){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new le(this.sourceBuffer),this.subscription.add(r(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(r(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),a=this.segments.get(e.id);if(l(i,'No init buffer for starting representation'),l(a,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let n=0;for(const t of a)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));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);l(e,`No such representation ${t}`);let i=this.initData.get(t);if(a(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 r=this.getCurrentPosition();s(r)&&this.maintain(r)}.bind(this));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(a(this.downloadingRepresentationId)||a(this.playingRepresentationId)||a(this.sourceBuffer))return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(l(e,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,i=Jt(this.sourceBuffer.buffered,t),a=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(r=a)}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,r),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&s)if(n.includes(s))t='high';else{const e=n.at(0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===ne.FED&&!n.length&&Jt(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=i.at(-1);o&&o.status===ne.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){const e=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!e)return;const i=this.segments.get(e);if(!i)return;return i.find((e=>e.time.from<=t&&e.time.to>=t))?.time.from??void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===ne.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==re.BYTE_RANGE)return t.slice(s,s+1);const a=t;let r=0;const n=[];for(let t=s;t<a.length&&r<=this.tuning.dash.segmentRequestSize;t++){const e=a[t];if(r+=e.byte.to+1-e.byte.from,e.status!==ne.NONE)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,a,r=t;const{type:o}=e.segmentReference;switch(o){case re.BYTE_RANGE:s=e.segmentReference.url,a={from:t.at(0).byte.from,to:t.at(-1).byte.to};break;case re.TEMPLATE:{const i=t.at(0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),r=[i];break}default:n(o)}for(const t of r)t.status=ne.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:pe.PARAM,range:a,onProgress:(t,i)=>{if(!d.aborted)try{this.onSomeDataLoaded(t,e.id,a?a.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){let e=!1;const i=this.getCurrentPosition();if(this.sourceBuffer&&s(i)){e=Jt(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,e||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,a){if(!this.activeSegments.size)return;const r=t=>{this.abortSegment(t.segment)},n=t=>{this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=ne.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const i of this.representations.values())if(i.id!==e)for(const e of this.segments.get(i.id)??[])e.status===ne.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=ne.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,h=t.byteLength;for(const o of this.activeSegments){const{segment:u}=o,c=d===re.BYTE_RANGE,l=c?u.byte.to-u.byte.from+1:h;if(o.representationId!==e)continue;if(!(!c||u.byte.from>=i&&u.byte.to<i+t.byteLength))continue;if(a.aborted){r(o);continue}const p=c?u.byte.from-i:0,m=p<s,f=(c?u.byte.to-i:t.byteLength)<=s;if(u.status===ne.DOWNLOADING&&m&&f){u.status=ne.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,l);this.sourceBufferTaskQueue.append(e,a).then((t=>t&&!a.aborted?n(o):r(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(l,s-p),o.loadedBytes>o.fedBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.fedBytes,o.loadedBytes-o.fedBytes),i=o.loadedBytes===l?e:this.containerParser.parseFeedableSegmentChunk(e);i?.byteLength&&(u.status=ne.PARTIALLY_FED,o.fedBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,a).then((t=>{!t||a.aborted?r(o):o.fedBytes===l&&n(o)})))}}}abortSegment(t){t.status===ne.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=ne.NONE)),t.status=ne.NONE):t.status=ne.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const a=s instanceof Promise;e||=a,null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=he((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,e='auto',i=!1){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',a=(!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,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,a),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,a),a}async pruneBuffer(t){const e=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||a(e))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let s=0,r=1/0,n=-1/0,o=!1;const d=t=>{r=Math.min(r,t.time.from),n=Math.max(n,t.time.to);const e='size'in t?t.size??0:t.byte.to-t.byte.from;s+=e};for(const a of i){if(a.time.to>=e||s>=t)break;a.status===ne.FED&&d(a)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=1/0,n=-1/0;for(const a of i){if(a.time.from<e+this.forwardBufferTarget||s>t)break;a.status===ne.FED&&d(a)}}return o=isFinite(r)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(r/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),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=he((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(a(this.sourceBuffer)||a(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!==ne.FED||i||(s.status=ne.NONE)}}}const _e=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===i?.[1]?-1:1;return 24*e(i?.[5],s)*60*60*1e3+60*e(i?.[6],s)*60*1e3+60*e(i?.[7],s)*1e3+1e3*e(i?.[8],s)},Ie=(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)=>a(e)?t:a(i)?e:e.padStart(parseInt(i,10),'0')))}return i},Le=['timeupdate','progress','play','seeked','stalled'];var Ce,xe;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Ce||(Ce={}));class Be{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new i;fetcher;state$=new z(Ce.NONE);currentVideoRepresentation$=new t(void 0);error$=new e;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);forceEnded$=new e;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new it;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new me({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=T(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(Ce.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 a;try{a=((t,e)=>{const i={video:[],audio:[],text:[]},a=(new DOMParser).parseFromString(t,'application/xml').children[0],r=a.getElementsByTagName('Period')[0],n=r.children;let o;const d=a.getAttribute('mediaPresentationDuration'),h=r.getAttribute('duration');if(d)o=_e(d);else if(h){const t=_e(h);s(t)&&(o=t)}let u=0;const c=a.getAttribute('profiles')?.split(',')??[],l=c.includes(ae.WEBM_AS_IN_FFMPEG)||c.includes(ae.WEBM_AS_IN_SPEC)?oe.WEBM:oe.MP4;for(const t of n){const s=t.getAttribute('mimeType'),a=t.getAttribute('codecs'),r=t.getAttribute('contentType')??s?.split('/')[0],n=t.getAttribute('profiles')?.split(',')??[],d=t.querySelectorAll('Representation');if('text'!==r)for(const h of d){const d=h.getAttribute('mimeType')??s,l=h.getAttribute('codecs')??a??'',p=h.getAttribute('contentType')??d?.split('/')[0]??r,m=t.getAttribute('profiles')?.split(',')??[],f=parseInt(h.getAttribute('width')??'',10),g=parseInt(h.getAttribute('height')??'',10),S=parseInt(h.getAttribute('bandwidth')??'',10)/1e3,b=h.getAttribute('frameRate')??'',v=h.getAttribute('quality')??void 0,y=b?Tt(b):void 0,T=`${h.getAttribute('id')??(u++).toString(10)}@${'video'===p?`${g}p`:'audio'===p?`${S}Kbps`:l}`,E=h.querySelector('BaseURL')?.textContent?.trim()??'',w=new URL(E,e).toString(),$=[...c,...n,...m];let k;const A=h.querySelector('SegmentBase'),P=h.querySelector('SegmentTemplate');if(A){const t=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[r,n]=a?a.split('-').map((t=>parseInt(t,10))):[],o=a?{from:r,to:n}:void 0;k={type:re.BYTE_RANGE,url:w,initRange:s,indexRange:o}}else{if(!P)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:h.getAttribute('id')??void 0,bandwidth:h.getAttribute('bandwidth')??void 0},e=parseInt(P.getAttribute('timescale')??'',10),i=P.getAttribute('initialization')??'',s=P.getAttribute('media'),a=parseInt(P.getAttribute('startNumber')??'',10)??1,r=Ie(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const n=P.querySelectorAll('SegmentTimeline S')??[],o=[];let d=a,u=0;for(const i of n){const a=1e3*parseInt(i.getAttribute('d')??'',10),r=parseInt(i.getAttribute('r')??'',10)||0,n=parseInt(i.getAttribute('t')??'',10)??void 0;for(let i=0;i<r+1;i++){const i=Ie(s,{...t,segmentNumber:d.toString(10),segmentTime:n.toString(10)}),r=n?n/e:u;u+=a/e;const h=u;d++,o.push({time:{from:r,to:h},url:i})}}k={type:re.TEMPLATE,baseUrl:w,initUrl:r,segments:o}}}if(!p||!d)continue;const D={video:se.VIDEO,audio:se.AUDIO,text:se.TEXT}[p];D&&i[D].push({id:T,kind:D,segmentReference:k,profiles:$,duration:o,bitrate:S,mime:d,codecs:l,width:f,height:g,fps:y,quality:v})}}return{duration:o,container:l,representations:i}})(i??'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!a)return null;const r=({mime:e,codecs:i})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${i}"`));return this.manifest={...a,representations:Object.fromEntries(Object.entries(a.representations).map((([t,e])=>[t,e.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(Ce.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this));initRepresentations=T(this.destroyController.signal,async function*(t,e){l(this.manifest),l(this.element),this.state$.startTransitionTo(Ce.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 Re(se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new Re(se.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 a=o(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(h((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),n=o(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(h((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(o(this.forceEnded$,y({allBuffersFull:a,someBufferEnded:n}).pipe(f((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{this.source?.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',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=>this.source?.addEventListener('sourceopen',t)))),s(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s(e)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Ce.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...Le.map((t=>r(this.element,t))),r(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(r(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(r(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&de(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this));async switchRepresentation(t,e){return{[se.VIDEO]:this.videoBufferManager,[se.AUDIO]:this.audioBufferManager,[se.TEXT]:null}[t]?.switchTo(e)}seek(t,e){let i;l(this.element),l(this.videoBufferManager),i=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(this.videoBufferManager.findSegmentStartTime(t)??t,this.audioBufferManager?.findSegmentStartTime(t)??t),de(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ce.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager?.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager?.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=w(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=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'}(xe||(xe={}));const Ne=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?Nt(r):void 0)??G({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Me=(t,e,i)=>{const s=e.indexOf(i);return t.at(Math.round(t.length*s/e.length))??t.at(-1)};class Oe{subscription=new i;videoState=new z(xe.STOPPED);video;player;params;elementSize$=new t(void 0);textTracksManager=new ft;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Dt;constructor(t){this.params=t,this.video=gt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(_t(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Be({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=yt(this.video),a=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,a));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),v(),g(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(lt(this.video,e.isLooped,a)),this.subscription.add(pt(this.video,e.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),n(It(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(xe.PLAYING),U(e.playbackState,P.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(xe.PAUSED),U(e.playbackState,P.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===xe.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(f((({to:t})=>t===Ce.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(xe.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$,r(this.video,'progress')).subscribe((()=>{const i=this.player.state$.getState(),s=this.player.state$.getTransition();if(i===Ce.NONE||!this.videoTracks.length)return;const a=i===Ce.MANIFEST_LOADED&&!s,r=i===Ce.REPRESENTATION_SELECTED&&!s,n=e.autoVideoTrackSwitching.getState(),o=e.videoTrack.getState(),h=this.videoTracks.find((({track:{id:t}})=>t===o))?.track,u=t.currentVideoTrack$.getValue(),c=Jt(this.video.buffered,1e3*this.video.currentTime),p=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(c/Math.min(p,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),f=Math.max(h&&!n?this.audioRepresentations.get(h.id)?.bitrate??0:0,u?this.audioRepresentations.get(u.id)?.bitrate??0:0),g=Rt(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),reserve:f,forwardBufferHealth:m,current:u,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=n?g??h:h??g;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(n),this.player.setBufferTarget(p)),a){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;l(t),this.player.initRepresentations(t.id,this.audioRepresentations.get(t.id)?.id)}else if(r){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(se.VIDEO,t.id).catch(d),e&&this.player.switchRepresentation(se.AUDIO,e.id).catch(d)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),h((t=>t&&this.videoTracks.find((({representation:{id:e}})=>e===t))?.track))).subscribe(t.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,e,t);const m=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,u(['init'])).pipe(p(0));this.subscription.add(m.subscribe(this.syncPlayback,a))}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=Ne(t);if(s){this.videoTracks.push({track:s,representation:t});const a=Me(e,i,t);a&&this.audioRepresentations.set(t.id,a)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(s.state===C.Requested&&i?.to!==P.PAUSED&&t!==xe.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===xe.STOPPED)return this.videoState.startTransitionTo(xe.READY),void this.prepare();switch(t){case xe.READY:return void(e===P.PAUSED?(this.videoState.setState(xe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(xe.PLAYING),this.playIfAllowed()));case xe.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(xe.PAUSED),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case xe.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(xe.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==xe.STOPPED&&(this.videoState.startTransitionTo(xe.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(xe.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(xe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Ue={};var Ve;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ve||(Ve={}));const qe=(t,e)=>new b((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class Fe{subscription=new i;videoState=new z(Ve.INITIALIZING);video;params;hls;textTracksManager=new ft;trackLevels=new Map;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(_t(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(Ue.Hls=e.default,Ue.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Ue.Hls,'hls.js not loaded'),this.hls=new Ue.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Ve.STOPPED)}subscribe(){l(Ue.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})},r=yt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadStart$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),this.subscription.add(lt(this.video,t.isLooped,i)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.hls,Ue.Events.ERROR).subscribe((t=>{t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${t.err?.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Ve.PLAYING),U(t.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ve.PAUSED),U(t.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ve.READY&&this.videoState.setState(Ve.READY),this.videoState.getState()===Ve.PLAYING&&this.playIfAllowed()}),i)),n(qe(this.hls,Ue.Events.MANIFEST_PARSED).pipe(h((({levels:t})=>t.reduce(((t,e)=>{const i=e.name||e.height.toString(10),{width:s,height:a}=e,r=Nt(e.attrs.QUALITY??'')??G({width:s,height:a});if(!r)return t;const n=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,o={id:i.toString(),quality:r,bitrate:e.bitrate/1e3,size:{width:s,height:a},fps:n};return this.trackLevels.set(i,{track:o,level:e}),t.push(o),t}),[])))),e.availableVideoTracks$),n(qe(this.hls,Ue.Events.LEVEL_LOADING).pipe(h((({url:t})=>_t(t)))),e.hostname$),this.subscription.add(ct(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=>Array.from(this.trackLevels.values()).find((({level:e})=>e===t))?.track,c=qe(this.hls,Ue.Events.LEVEL_SWITCHED).pipe(h((({level:t})=>d(this.hls.levels[t]))));c.pipe(f(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(ct(t.videoTrack,(()=>d(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(a(t))return;const e=this.trackLevels.get(t)?.level;if(!e)return;const i=this.hls.levels.indexOf(e),s=this.hls.currentLevel,r=this.hls.levels[s];!r||e.bitrate>r.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:c.pipe(h((t=>t?.id))),onError:i})),n(r.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$,u(['init'])).pipe(p(0));this.subscription.add(m.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(t!==Ve.INITIALIZING)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case Ve.STOPPED:break;case Ve.READY:case Ve.PLAYING:case Ve.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Ve.PLAYING:break;case Ve.STOPPED:this.prepare();break;case Ve.READY:case Ve.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case Ve.PAUSED:break;case Ve.STOPPED:this.prepare();break;case Ve.READY:this.videoState.setState(Ve.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case Ve.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}};prepare(){this.videoState.startTransitionTo(Ve.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Ve.PLAYING);await Mt(this.video)||(this.videoState.setState(Ve.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Ve.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(Ve.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}}const He=t=>{let e=null;if(t.QUALITY&&(e=Nt(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=G({width:i,height:s})}return e??null},Ge=async(t,e=t)=>{const i=await et(t),s=(await i.text()).split('\n'),a=[];for(let t=0;t<s.length;t++){const i=s[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!i)continue;const r=Object.fromEntries(i[1].split(',').map((t=>t.split('=')))),n=r.QUALITY??`stream-${r.BANDWIDTH}`,o=He(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let u;if(r.RESOLUTION){const[t,e]=r.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(u={width:t,height:e})}const c=new URL(s[++t],e).toString();o&&a.push({id:n,quality:o,url:c,bandwidth:d,size:u,fps:h})}return a};var Ye,ze,Qe;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Ye||(Ye={}));class We{subscription=new i;videoState=new z(Ye.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);maxSeekBackTime$;liveOffset=new St;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:M.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Ge(O(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([i,...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(_t(this.params.source.url)),this.maxSeekBackTime$=new t(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},a=yt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(pt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Ye.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ye.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ye.READY&&this.videoState.setState(Ye.READY),this.videoState.getState()===Ye.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),h((t=>-t/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(_t(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Ye.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(a.loadedData$.subscribe((()=>{const t=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(t||void 0)}),i)),this.subscription.add(y({startTime:this.manifestStartTime$.pipe(f(s)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,u(['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(a(t))return;const e=O(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=>{a(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Ye.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()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Ye.STOPPED&&(this.videoState.startTransitionTo(Ye.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(Ye.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===Ye.STOPPED)return this.videoState.startTransitionTo(Ye.READY),void this.prepare();if(s||a){const t=this.videoState.getState();return this.videoState.setState(Ye.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if(i?.to!==P.PAUSED&&r.state===C.Requested)return this.videoState.startTransitionTo(Ye.READY),this.seek(r.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Ye.READY:return void(e===P.PAUSED?(this.videoState.setState(Ye.PAUSED),this.liveOffset.pause(),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Ye.PLAYING),this.playIfAllowed()));case Ye.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Ye.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Ye.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Ye.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):i?.to===P.PAUSED&&(U(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Ye.CHANGING_MANIFEST:break;default:return n(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(ze||(ze={}));class je{subscription=new i;videoState=new z(ze.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video);const e={id:'master',quality:M.INVARIANT,url:this.params.source.url};this.manifests$.next([e]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(_t(this.params.source.url)),Ge(this.params.source.url).then((t=>{this.manifests$.next([e,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},a=yt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),r(a.seeked$,t.seekedEvent$),this.subscription.add(lt(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(ze.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(ze.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ze.READY&&this.videoState.setState(ze.READY),this.videoState.getState()===ze.PLAYING&&this.playIfAllowed()}),i).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(_t(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===ze.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===C.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(h((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['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();a(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(ze.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==ze.STOPPED&&(this.videoState.startTransitionTo(ze.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(ze.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===ze.STOPPED)return this.videoState.startTransitionTo(ze.READY),void this.prepare();if(s||a){const t=this.videoState.getState();this.videoState.setState(ze.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case ze.READY:return void(e===P.PAUSED?(this.videoState.setState(ze.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(ze.PLAYING),this.playIfAllowed()));case ze.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(ze.PAUSED),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case ze.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(ze.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));case ze.CHANGING_MANIFEST:break;default:return n(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Qe||(Qe={}));class Je{subscription=new i;videoState=new z(Qe.STOPPED);video;trackUrls={};params;textTracksManager=new ft;constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=yt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),r(a.seeked$,t.seekedEvent$),this.subscription.add(lt(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Qe.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Qe.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Qe.READY&&this.videoState.setState(Qe.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&s(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===Qe.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$,u(['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(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();l(t,'MpegProvider: track is not selected');let{url:e}=this.trackUrls[t];l(e,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(e=ht(e)),this.video.setAttribute('src',e),this.video.load(),this.params.output.hostname$.next(_t(e))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Qe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==Qe.STOPPED&&(this.videoState.startTransitionTo(Qe.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Qe.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(t===Qe.STOPPED)return this.videoState.startTransitionTo(Qe.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case Qe.READY:return void(e===P.PAUSED?(this.videoState.setState(Qe.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Qe.PLAYING),this.playIfAllowed()));case Qe.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Qe.PAUSED),this.video.pause()):i?.to===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Qe.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Qe.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}}class Xe{iterator;current;constructor(t){this.iterator=t[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const Ke=ue(),Ze=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),ti=document.createElement('video'),ei={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(ti.canPlayType?.('application/x-mpegurl')||ti.canPlayType?.('vnd.apple.mpegURL'))},ii={mp4:Boolean(ti.canPlayType?.('video/mp4')),webm:Boolean(ti.canPlayType?.('video/webm'))},si={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},ai=(si.h264||si.h265)&&si.aac,ri=!Ke,ni=ei.hls&&ii.mp4&&(Ze||Ke);const oi=3e4,di=18e4,hi=3,ui=100,ci={cacheDuration:12e4},li={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},pi={maxPausedTime:3e4},mi={maxPausedTime:3e4};class fi{current$=new t({type:void 0});providerError$=new e;noAvailableProvidersError$=new e;providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,canplay$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)};subscription=new i;screenFormatsIterator;chromecastFormatsIterator;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:e}=this.params.tuning,i=e.length?[...t.screenFormatsPriority.filter((t=>!e.includes(t))),...t.screenFormatsPriority.filter((t=>e.includes(t)))]:t.screenFormatsPriority;this.screenFormatsIterator=new Xe(((t,e=!1)=>t.filter((t=>{switch(t){case D.DASH:return ei.mse&&ii.mp4&&ai&&ri;case D.DASH_SEP:return ei.mse&&ii.mp4&&ai;case D.DASH_WEBM:return ei.mse&&ii.webm&&si.vp9&&si.opus;case D.DASH_LIVE:case D.DASH_ONDEMAND:return ei.mse&&ii.mp4&&ai;case D.HLS:case D.HLS_LIVE:case D.HLS_ONDEMAND:return ni||e&&ei.mse&&ii.mp4&&ai;case D.MPEG:return ii.mp4;case D.DASH_LIVE_WEBM:return!1;default:return n(t)}})))(i.filter((e=>s(t.sources[e]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Xe(t.chromecastFormatsPriority.filter((e=>s(t.sources[e]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),e=this.chooseFormat(t);if(a(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;l(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case R.SCREEN:return this.createScreenProvider(e);case R.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,a={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 l(i),new ie({...a,source:i,config:ci})}case D.DASH_SEP:case D.DASH_WEBM:case D.DASH_ONDEMAND:{const i=e[t];return l(i),this.params.tuning.useDashJs?new Bt({...a,source:i,format:t,config:mi}):new Oe({...a,source:i})}case D.HLS:case D.HLS_ONDEMAND:{const i=e[t];return l(i),ni||!this.params.tuning.useHlsJs?new je({...a,source:i}):new Fe({...a,source:i})}case D.HLS_LIVE:{const i=e[t];return l(i),new We({...a,source:i,config:pi})}case D.MPEG:{const i=e[t];return l(i),new Je({...a,source:i})}case D.DASH_LIVE:{const i=e[t];return l(i),new Wt({...a,source:i,config:li})}case D.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:a}=this.params,r=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new W({connection:n,meta:a,container:i,source:e,format:t,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?R.CHROMECAST:R.SCREEN}chooseFormat(t){switch(t){case R.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case R.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case R.SCREEN:return this.screenFormatsIterator.next();case R.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case R.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case R.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let t=[],a=0;const r=new i;var n;return r.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:oi,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(f((({type:t})=>void 0!==t)))},new b((t=>{const s=new i,a=n.desiredPlaybackState$.stateChangeStarted$.pipe(h((({from:t,to:e})=>`${t}-${e}`))),r=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let u=0,c='unknown';return s.add(a.subscribe((t=>{u&&window.clearTimeout(u),c=t,u=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(r.subscribe((()=>{window.clearTimeout(u),c='provider change',u=0}))),s.add(o.subscribe((()=>{u&&(window.clearTimeout(u),u=window.setTimeout((()=>d.next(c)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(u),s.unsubscribe()}}))).pipe(h((t=>({id:`ProviderHangup:${t}`,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),r.add(this.providerError$.pipe($(ui,{leading:!1,trailing:!0})).subscribe((()=>{const e=Date.now();this.current$.getValue().destination===R.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(t[a])&&e<t[a]+di?(t=[],this.switchToNextProvider()):(t[a]=e,this.reinitProvider()),a=(a+1)%hi}))),r}}const gi=(t,e,i)=>i*e+(1-i)*t;class Si{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const i=e.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new At(`raw_${i}`),this.smoothedSeries$=new At(`smoothed_${i}`),this.reportedSeries$=new At(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=(this.pastMeasures[t]-this.smoothed)**2,i++);e/=i;const s=Math.sqrt(e),r=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=gi(this.slow,t,this.params.emaAlphaSlow),this.fast=gi(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>r||this.smoothed<n||(a(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 bi;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(bi||(bi={}));const vi=new Map;let yi=bi.RUNTIME;const Ti=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Ti,'test'),localStorage.removeItem(Ti),yi=bi.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Ti),yi=bi.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;yi=bi.RUNTIME}}})();const Ei=(t,e)=>{switch(yi){case bi.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case bi.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case bi.RUNTIME:return void vi.set(t,e);default:n(yi)}},wi=window.navigator.connection,$i=()=>{const t=wi?.downlink;if(s(t)&&10!==t)return 1e3*t},ki=()=>{const t=wi?.rtt;if(s(t)&&3e3!==t)return t},Ai=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Pi{throughput;rtt;subscription=new i;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=Pi.load('one_video_throughput')||(e.useBrowserEstimation?$i():void 0)||5e3,a=Pi.load('one_video_rtt')??(e.useBrowserEstimation?ki():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(Ai(i,a,e.rttPenaltyRequestSize)),this.throughput=new Si({initial:i,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Si({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=$i();t&&this.throughput.next(t);const e=ki();s(e)&&this.rtt.next(e)};wi&&'onchange'in wi&&this.subscription.add(r(wi,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Ei('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Ei('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(h((({throughput:t,rtt:i})=>Ai(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=S();const a=new i;switch(this.subscription.add(a),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:a.add(r(t,'progress').pipe(v()).subscribe((t=>{e=t.loaded,s=S()})));break;case 1:case 0:a.add(r(t,'loadstart').subscribe((()=>{e=0,s=S()})))}a.add(r(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,a=S(),r=t-e,n=a-s;this.addRawSpeed(r,n,1)}this.concurrentDownloads.delete(t),a.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=S();let a=0,r=S();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:d,value:h})=>{d?(this.addRawSpeed(i,S()-s,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,a+=h.byteLength,a>=this.tuningConfig.streamMinSampleSize&&S()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,S()-r,this.concurrentDownloads.size),a=0,r=S()),await(e?.read().then(o,n)))};this.concurrentDownloads.add(t),e?.read().then(o,n)}addRawSpeed(t,e,i=1){if(Pi.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){const e=(t=>{switch(yi){case bi.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case bi.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case bi.RUNTIME:return vi.get(t);default:n(yi)}})(t);if(s(e))return parseInt(e,10)??void 0}}const Di={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0};const Ri=(t=(t=>t))=>({playbackState:e,seekState:s,playbackAbort$:r,looped$:n,position$:d})=>new b((u=>{let c;const l=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})=>t.state===C.Requested&&(e.getTransition()?.from??e.getState())===P.PLAYING))),g=s.stateChangeEnded$.pipe(f((({from:t,to:i})=>t.state===C.Applying&&i.state===C.None&&(e.getTransition()?.from??e.getState())===P.PLAYING))),S=o(l,g).pipe(h((()=>t(d.getValue())))),b=o(o(p,m,r).pipe(h((()=>t(d.getValue())))),n.pipe(h(t)));return(new i).add(S.subscribe((e=>{c=t(e)}))).add(b.subscribe((e=>{const i=t(e);if(a(c)||c===i)return;const s={from:c,to:i};c=void 0,u.next(s)})))})),_i=Ri((t=>t)),Ii=Ri((t=>Math.round(1e3*t)+Date.now())),Li={[R.SCREEN]:{vod:[...ni?[D.HLS,D.HLS_ONDEMAND]:[],D.DASH_WEBM,D.DASH_SEP,D.DASH,D.DASH_ONDEMAND,...ni?[]:[D.HLS,D.HLS_ONDEMAND],D.MPEG],live:ni?[D.HLS_LIVE,D.DASH_LIVE]:[D.DASH_LIVE,D.HLS_LIVE]},[R.CHROMECAST]:{vod:[D.DASH_WEBM,D.DASH_SEP,D.DASH_ONDEMAND,D.HLS,D.HLS_ONDEMAND,D.MPEG],live:[D.HLS_LIVE]}};class Ci{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new k;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;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({})};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(_.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)};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};experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:$t};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Di)){const s=Di[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:a??s}return e})(t),this.chromecastInitializer=new x({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Pi(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}>`})))),a=`Player.${String(e)}`,r=`Exception calling ${a} (${s.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:t}),t}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new fi({screenFormatsPriority:[...Li[R.SCREEN].live,...Li[R.SCREEN].vod],chromecastFormatsPriority:[...Li[R.CHROMECAST].live,...Li[R.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){l(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){return(void 0===t||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t)))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){l(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(a(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(h((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(h((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=S(),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),v()).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(h((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(h((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(h((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(t?.quality),this.info.videoBitrate$.next(t?.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).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(h((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(h((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(h((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekState:t,position$:e})=>o(t.stateChangeEnded$.pipe(h((({to:t})=>t.state===C.None?void 0:(t.position??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(g(!0)),e.providerOutput.seekedEvent$.pipe(g(!1))).pipe(c()).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(h((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(v(),h((()=>S()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(v(),h((()=>S()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(v(),h((()=>S()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const a=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>a.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>a.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)),v()).subscribe((()=>n.next(!1))));let d=0;const u=o(e.providerOutput.isBuffering$,a,n).pipe(h((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=a.getValue()||n.getValue();return t&&!i})),c());this.subscription.add(u.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(r(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(f((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),p.unsubscribe(),t){case!0:p.add(Ii({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:m,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).pipe(h((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break;case!1:p.add(_i({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:m,position$:this.providerContainer.providerOutput.position$}).pipe(h((({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(h((t=>t?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(f((t=>t.length>0)),v()).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=Rt(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(h((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(h((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(h((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(h((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const t=this.providerContainer?.providerOutput;l(this.providerContainer),l(t),wt={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Et=t})),this.providerContainer.current$.subscribe((({type:t})=>kt('provider',t))),t.duration$.subscribe((t=>kt('duration',t))),t.availableVideoTracks$.pipe(f((t=>!!t.length)),v()).subscribe((t=>kt('tracks',t))),this.events.fatalError$.subscribe(new At('fatalError')),this.events.managedError$.subscribe(new At('managedError')),t.position$.subscribe(new At('position')),t.currentVideoTrack$.pipe(h((t=>t?.quality))).subscribe(new At('quality')),this.info.currentBuffer$.subscribe(new At('buffer')),t.isBuffering$.subscribe(new At('isBuffering'))].forEach((t=>this.subscription.add(t))),kt('codecs',Object.keys(si).filter((t=>si[t])))}}const xi='@vkontakte/videoplayer-core@2.0.68';export{_ as ChromecastState,L as HttpConnectionType,P as PlaybackState,Ci as Player,xi as SDK_VERSION,I as StartStatus,D as VideoFormat,M as VideoQuality};