@vkontakte/videoplayer-core 2.0.75 → 2.0.76

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.75
3
- * Wed, 07 Dec 2022 13:50:44 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-75/doc/
2
+ * @vkontakte/videoplayer-core v2.0.76
3
+ * Wed, 14 Dec 2022 00:36:28 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-76/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,combine as f,once as g,mapTo as S,filter as b,now as v,Observable 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,R,D,_,C,I;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS',t.HLS_LIVE='HLS_LIVE',t.WEB_RTC_LIVE='WEB_RTC_LIVE'}(R||(R={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(D||(D={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(_||(_={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(C||(C={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(I||(I={}));class L{connection$=new t(void 0);castState$=new t(_.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(_.NOT_AVAILABLE);subscription=new i;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const e='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${e}`}),t.isDisabled||!e)return;const i=s(window.chrome?.cast),a=Boolean(window.__onGCastApiAvailable);var r;i?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{delete window.__onGCastApiAvailable,t&&this.initializeCastApi()},a||(r='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',r),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).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(x),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 x=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _.AVAILABLE;case cast.framework.CastState.CONNECTING:return _.CONNECTING;case cast.framework.CastState.CONNECTED:return _.CONNECTED;default:return n(t)}};var B;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(B||(B={}));var N,M=(t,e=0,i=B.OFFSET_P)=>{switch(i){case B.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case B.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},O=(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'}(N||(N={}));const U={[N.Q_144P]:{width:256,height:144},[N.Q_240P]:{width:428,height:240},[N.Q_360P]:{width:640,height:360},[N.Q_480P]:{width:856,height:480},[N.Q_720P]:{width:1280,height:720},[N.Q_1080P]:{width:1920,height:1080},[N.Q_1440P]:{width:2560,height:1440},[N.Q_2160P]:{width:3840,height:2160},[N.Q_4320P]:{width:7680,height:4320}},V=(t,e)=>U[t].height>U[e].height,q=(t,e)=>U[t].height<U[e].height,F=Object.keys(U).sort(((t,e)=>q(t,e)?-1:1)),H=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return F.find((t=>{const e=U[t];return e.width>=s&&e.height>=i}))},G=t=>t===N.INVARIANT;class Y{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 z;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(z||(z={}));class Q{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new Y(z.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case R.MPEG:case R.DASH:case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:case R.HLS:case R.HLS_ONDEMAND:return!1;case R.HLS_LIVE:case R.DASH_LIVE:case R.DASH_LIVE_WEBM:case R.WEB_RTC_LIVE:return!0;default:return 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===I.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(),O(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(z.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(z.PLAYING),O(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:I.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==z.PAUSED&&t!==z.PLAYING||(this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==z.PLAYING&&t!==z.PAUSED||(this.videoState.setState(z.PLAYING),O(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY)}handleRemoteStop(){this.videoState.getState()!==z.STOPPED&&this.videoState.setState(z.STOPPED)}handleRemoteVolumeChange(t){const e=this.params.output.volume$.getValue(),i={volume:t.volume??e.volume,muted:t.muted??e.muted};i.volume===e.volume&&i.muted==i.muted||this.params.output.volume$.next(i)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){const e=this.params.source;let i,a,r;switch(t){case R.MPEG:{const s=e[t];l(s);const n=Object.keys(s).sort(((t,e)=>t===e?0:t===N.INVARIANT?1:e===N.INVARIANT?-1:q(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 R.HLS:case R.HLS_ONDEMAND:{const s=e[t];l(s),i=s.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:{const s=e[t];l(s),i=s.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case R.HLS_LIVE:{const s=e[t];l(s),i=M(s.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case R.DASH:case R.DASH_LIVE:case R.WEB_RTC_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}case R.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===I.Applying||i.state===I.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===I.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!==I.Requested||t===z.STOPPED)switch(i){case P.PLAYING:switch(t){case z.PLAYING:break;case z.PAUSED:case z.READY:this.videoState.startTransitionTo(z.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case z.PLAYING:this.videoState.startTransitionTo(z.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case z.PAUSED:break;case z.READY:this.videoState.startTransitionTo(z.PAUSED),this.videoState.setState(z.PAUSED);break;case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();break;default:n(t)}break;default:n(i)}else this.seek(a.position)}else t!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.stop())}}class W{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}removeEventListener(t,e){if(!(t in this.listeners))return;const i=this.listeners[t];for(let t=0,s=i.length;t<s;t++)if(i[t].callback===e)return void i.splice(t,1)}dispatchEvent(t){if(!(t.type in this.listeners))return;const e=this.listeners[t.type].slice();for(let i=0,s=e.length;i<s;i++){const s=e[i];try{s.callback.call(this,t)}catch(t){Promise.resolve().then((()=>{throw t}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}class j extends W{constructor(){super(),this.listeners||W.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class J{constructor(){Object.defineProperty(this,'signal',{value:new j,writable:!0,configurable:!0})}abort(){let t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event'),t.initEvent('abort',!1,!1)):(t=document.createEventObject(),t.type='abort'):t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}toString(){return'[object AbortController]'}}function X(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(J.prototype[Symbol.toStringTag]='AbortController',j.prototype[Symbol.toStringTag]='AbortSignal');const K=X({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Z=K?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=t;if(!X({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const a=new i(t,e);return s&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),a},r.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=r&&r.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const a=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,n(t,e)])}return n(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,tt=K?Z.fetch:window.fetch;K?Z.Request:window.Request;const et=K?J:window.AbortController,it=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class st{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){const{url:e}=t.request,i=this.dashJsRequestQueue.get(e)??[];i.push(t),this.dashJsRequestQueue.set(e,i)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=it(s.request);if(a>=i.from&&r<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){if(t){const{request:e}=t,i=(this.dashJsRequestQueue.get(e.url)??[]).includes(t),s=this.activeRequests.get(e.url);i&&s&&s.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(it),s=i[0][0];let 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 et,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 tt(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,st.suppressStreamErrors).catch(u)))};r?.read().then(d,st.suppressStreamErrors).catch(u)}),st.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]=it(n),u=d>=e&&h<=e+s,c=e>=d&&e+s<h,l=a.slice(d-e,Math.min(h-e+1,s));if((u||c)&&(n.requestStartDate=n.requestStartDate??new Date,n.firstByteDate=n.firstByteDate??new Date,n.bytesLoaded=l.byteLength,n.bytesTotal=i-e),u){n.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(this.dashJsRequestQueue.get(t)??[]).filter((t=>t!==o))),o.success?.(l,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';this.dashMetrics?.addHttpRequest(n,t,r?.status??200,e,[])}else c&&o.progress?.({loaded:s,total:i-e,lengthComputable:!0,stream:!0})}}onBigRequestError({url:t,from:e,to:i},s){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const a=this.dashJsRequestQueue.get(t)??[];for(const t of a){const[a,r]=it(t.request);(a>=e&&a<i||r>e&&r<=i)&&t?.error?.(t.request,String(s))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){if(!this.activeRequests.has(t))return;const s=this.dashJsRequestQueue.get(t)??[];for(const t of s){const[s,a]=it(t.request);(s>=e&&s<i||a>e&&a<=i)&&t?.abort?.(t.request)}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class at{baseLoader;config;bigRequest;constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(at.shouldDelegateToBase(e))return this.baseLoader.load(t);this.bigRequest.queueDashJSRequest(t),this.bigRequest.executeNextRequests()}abort(t){if(!t)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:e}=t;at.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const rt=(t,e)=>{const i=new st(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new at(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var nt=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&e?.()})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&e?.()}}}),!0)},ot=i=>{const a=new t(1/0),r=new e,n=new t(void 0),o=new t(void 0);let d=NaN,h=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{const e=Object.fromEntries(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in e||'x-playback-duration-millis'in e){const e=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),i=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*e??NaN;s(i)&&!isNaN(i)&&a.next(i)}const i=e['x-delivery-type']??C.HTTP1,r={1:!0,0:!1}[e['x-reused']]??void 0;n.next(i),o.next(r)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!h&&(h=!0,r.next(Date.now()-d)),i(...t)},d=Date.now(),h=!1}return e(t)}}}),!0),{playbackDuration$:a,ping$:r,connectionReused$:o,connectionType$:n}},dt=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},ht=t=>{t.extend('HTTPLoader',(function(){const{parent:t}=this,e=t.load;return{load:t=>{if(t.request&&t.request.range){const[e,i]=t.request.range.split('-').map((t=>parseInt(t,10))),s=new URL(t.request.url,location.href);s.searchParams.append('bytes',`${e}-${i}`),t.request.url=s.toString(),t.request.range=void 0}e(t)}}}),!0)};const ut=(t,e,s,{equal: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},ct=(t,e,i)=>ut(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),lt=(t,e,i,a)=>ut(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||t?.muted===e?.muted&&t?.volume===e?.volume,changed$:i,onError:a}),pt=(t,e,i,a)=>ut(e,(()=>t.playbackRate),(e=>{s(e)&&(t.playbackRate=e)}),{changed$:i,onError:a}),mt=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class ft{available$=new e;current$=new t(void 0);error$=new e;video;cueSettings;subscription=new i;externalTracks=new Map;connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const 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(ut(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(h((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(ut(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:a})),this.subscription.add(ut(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'),e.setAttribute('poster','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='),t.appendChild(e),e};class St{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}var bt=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};class vt{_buffer=[];_source;constructor(t){this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:a})=>{const r=s>=t&&s<e,n=a>=t&&a<e;r&&n||(r?i(e,a):n?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var yt=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(s=n,a=o,!i)return{from:s,to:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{from:s,to:a}};const Tt=t=>{const i=e=>r(t,e).pipe(S(void 0)),a=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>r(t,e)))).pipe(h((e=>'ended'===e.type?t.readyState<2:t.readyState<3)),c()),n=o(r(t,'progress'),r(t,'timeupdate')).pipe(h((()=>yt(t.buffered,t.currentTime)))),d=bt()?f({play:i('play').pipe(g()),playing:i('playing')}).pipe(S(void 0)):i('playing'),u=r(t,'volumechange').pipe(h((()=>({muted:t.muted,volume:t.volume})))),l=r(t,'ratechange').pipe(h((()=>t.playbackRate))),p=r(t,'error').pipe(b((()=>Boolean(t.error||t.played.length))),h((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element',thrown:t.error??void 0}}))),m=r(t,'timeupdate').pipe(h((()=>t.currentTime))),v=new e;let y;return m.subscribe((e=>{t.loop&&s(y)&&s(e)&&y>=t.duration-.3&&e<=.3&&v.next(y),y=e})),{playing$:d,pause$:i('pause').pipe(b((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:v,error$:p,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:m,durationChange$:r(t,'durationchange').pipe(h((()=>t.duration))),isBuffering$:a,currentBuffer$:n,volumeState$:u,playbackRateState$:l}},Et=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};let wt=!1,$t={};const kt=t=>{t($t)},At=(t,e)=>{wt&&($t.meta=$t.meta??{},$t.meta[t]=e)};class Pt{name;constructor(t){this.name=t}next(t){if(!wt)return;$t.series=$t.series??{};const e=$t.series[this.name]??[];e.push([Date.now(),t]),$t.series[this.name]=e}}const Rt=new Pt('best_bitrate');class Dt{last;history={};recordSelection(t){this.history[t.id]=v()}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&&H(p),f=r.considerPlaybackRate&&s(h)?h:1,g=t.filter((t=>!G(t.quality))).sort(((t,e)=>V(t.quality,e.quality)?-1:1)),S=g.at(-1)?.quality,b=g.at(0)?.quality,y=a(n)||s(n.min)&&s(n.max)&&q(n.max,n.min)||s(n.min)&&b&&V(n.min,b)||s(n.max)&&S&&q(n.max,S),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||q(t.quality,m),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*T,c=r.lazyQualitySwitch&&s(r.minBufferToSwitchUp)&&u&&!G(u.quality)&&(d??0)<r.minBufferToSwitchUp&&V(t.quality,u.quality),l=y||(a(n.max)||(p=t.quality,f=n.max,U[p].height<=U[f].height))&&(a(n.min)||((t,e)=>U[t].height>=U[e].height)(t.quality,n.min));var p,f;return e&&h&&!c&&l}))[0];k&&k.bitrate&&Rt.next(k.bitrate);const A=k??g[Math.ceil((g.length-1)/2)]??t[0],P=A&&c&&c.history[A.id]&&v()-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 Ct=t=>new URL(t).hostname;const It=(t,e=300)=>new y((i=>{const{width:a,height:r}=t.getBoundingClientRect();if(i.next({width:a,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let a,r;e.contentBoxSize&&e.contentBoxSize[0]?(r=e.contentBoxSize[0].blockSize,a=e.contentBoxSize[0].inlineSize):e.contentRect&&(a=e.contentRect.width,r=e.contentRect.height),s(a)&&s(r)&&i.next({width:a,height:r})}),e));return n.observe(t),()=>n.disconnect()})),Lt={};var xt;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(xt||(xt={}));const Bt=(t,e)=>new y((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Nt{subscription=new i;videoState=new Y(xt.DOWNLOADING_LIB);video;player;params;textTracksManager=new ft;videoTracks=[];frameRatesByFrameHeight={};isLive$=new t(void 0);maxSeekBackTime$=new t(1/0);availableFrom$=new t(void 0);elementSize$=new t(void 0);liveOffset=new St;destroyBigRequest;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Ct(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?Et(t.frameRate+''):void 0),!0)));(this.params.format===R.DASH_WEBM||this.params.format===R.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=rt(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&ht(this.player),nt(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:dt})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(xt.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(It(this.video),this.elementSize$),r(Bt(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(Bt(this.player,'playbackError').pipe(h((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Bt(this.player,'qualityChangeRendered').pipe(b((({mediaType:t})=>'video'===t)),h((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));n.pipe(b(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(b((({to:t})=>t===xt.STREAM_INITIALIZED)),g()).subscribe((()=>{this.subscription.add(ut(e.videoTrack,(()=>{const t=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track?.id}),(t=>{if(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(ut(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),r(Bt(this.player,'bufferStateChanged').pipe(b((({mediaType:t})=>'video'===t)),h((({state:t})=>'bufferStalled'===t))),t.isBuffering$),r(Bt(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')??C.HTTP1,n={1:!0,0:!1}[a]??void 0;this.params.output.httpConnectionType$.next(r),this.params.output.httpConnectionReused$.next(n),t.hostname$.next(Ct(i))})),r(Bt(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=H(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(xt.STREAM_INITIALIZED),this.videoState.startTransitionTo(xt.READY)})),r(Bt(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(f({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(b(s))}).pipe(b((({isLive:t})=>t)),h((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const d=Bt(this.player,'playbackTimeUpdated').pipe(h((({time:t})=>t??0)));r(f({availableFrom:this.availableFrom$.pipe(b(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(d.pipe(b((()=>!1===this.isLive$.getValue()))),t.position$),r(Bt(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),r(Bt(this.player,'playbackEnded'),t.endedEvent$),r(Bt(this.player,'playbackProgress').pipe(h((()=>yt(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),r(Bt(this.player,'playbackPlaying'),(()=>{this.videoState.setState(xt.PLAYING),O(e.playbackState,P.PLAYING)})),r(Bt(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(xt.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(Bt(this.player,'playbackPaused'),(()=>{this.videoState.setState(xt.PAUSED),O(e.playbackState,P.PAUSED)})),r(Bt(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===xt.READY&&this.videoState.setState(xt.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$:v}=ot(this.player);r(m,this.params.output.httpConnectionType$),r(v,this.params.output.httpConnectionReused$),r(c,this.maxSeekBackTime$),r(l.pipe(g()),t.firstBytesEvent$),r(Bt(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(f({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(b((t=>t>this.params.tuning.insufficientBufferRuleMargin)),g()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Bt(this.player,'manifestLoaded').pipe(g()).subscribe((()=>{this.subscription.add(Bt(this.player,'playbackPlaying').pipe(g(),S(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(ct(this.video,e.isLooped,i));const{volumeState$:y,looped$:T,playbackRateState$:E}=Tt(this.video);this.subscription.add(lt(this.video,e.volume,y,i)),this.subscription.add(y.subscribe(t.volume$,i)),this.subscription.add(T.subscribe(t.loopedEvent$)),this.subscription.add(pt(this.video,e.playbackRate,E,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(xt.STOPPED),O(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(xt.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=M(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,B.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(xt.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(xt.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==xt.DOWNLOADING_LIB&&t!==xt.STREAM_INITIALIZED)switch(i?.to!==P.PAUSED&&s.state===I.Requested&&t!==xt.STOPPED&&e!==P.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case xt.STOPPED:break;case xt.PLAYING:case xt.PAUSED:case xt.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case xt.PLAYING:break;case xt.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case xt.READY:this.play();break;case xt.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case xt.PLAYING:this.pause(),this.liveOffset.pause();break;case xt.PAUSED:break;case xt.READY:this.videoState.setState(xt.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED);break;case xt.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 Mt=t=>{switch(t){case'mobile':return N.Q_144P;case'lowest':return N.Q_240P;case'low':return N.Q_360P;case'sd':case'medium':return N.Q_480P;case'hd':case'high':return N.Q_720P;case'fullhd':case'full':return N.Q_1080P;case'quadhd':case'quad':return N.Q_1440P;case'ultrahd':case'ultra':return N.Q_2160P}},Ot=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function Ut(){return v()}function Vt(t){return Ut()-t}function qt(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 Ft(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=Vt(h);let e;if(t<S)return e=S-t,void setTimeout(b,e);S*=2,S>g&&(S=g),o&&o.abort(),o=new r,y()};const v=()=>{if(!c){if(--p>=0)return b(),void(a&&a());c=!0,u&&u(),i&&i()}},y=()=>{h=Ut(),o=new r,o.open('get',t);let i,s=0,a=0;const p=()=>(l(h),Math.max(h,Math.max(i||0,a||0)));if(n&&o.addEventListener('progress',(t=>{const e=Ut();n.updateChunk&&t.loaded>s&&(n.updateChunk(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=Ut(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=f,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(m=t,T),withJSONResponse:()=>(f='json',T),withRetryCount:t=>(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 Ht{intervals=[];currentRate=0;logger;constructor(t){this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const n=t.bytes*a/r;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:'warn'}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}}class Gt{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(t,e,i,s,a){this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=Ut(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=Ft(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Ut()-i,delete this.activeRequests[e],this._sendPending(),t._cb?t._cb(s,t._downloadTime):(this.limitCompleteCount(),this.completeRequests[e]=t)}),(()=>s('error')),(()=>{t._retry=1,t._retryCB&&t._retryCB()})),t._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{t._finallyCB&&t._finallyCB()})),this.activeRequests[e]=t,t._request.send(),this.lastPrefetchStart=Ut()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const t=this._getParallelRequestCount(),e=Ut();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class Yt{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(t){this.params=t,this.chunkRateEstimator=new Ht(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=qt(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=qt(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(()=>{Boolean(t.error)&&!this.destroyed&&(e(`Video element error: ${t.error?.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),console.log('Live set video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gt(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback: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=Ft(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=Ut()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const a=this.bufferStates[e];t=Math.min(t,a.buf),a.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,g(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else g(1)},v=t=>{let i;const 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=Ft(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=Ut(),s=Math.min(1e4,e-i);w=i;const a=()=>{u||p()&&E.seek((()=>{p()&&(w=Ut(),k(),$())}))};s>0?g=window.setTimeout((()=>{this.paused?$():a()}),s):a()},k=()=>{let e;for(;e=E.nextChunk(c);)c=e,_(e);const i=E.nextChunk(h);if(i){if(h&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));D(i)}else $()},A=(t,e)=>{if(!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=Ut(),h=i.currentTime;!this.paused&&i.buffered.length>1&&S===h&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),S!==h&&(S=h,T=d);const u=this._getBufferSizeSec();if(u>30)s(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(a=this.sourceBuffer.buffered.start(0),r=h,r-a>4&&this.sourceBuffer.remove(a,r-3)),o(1e3)}}},P=()=>{d&&r&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),A(d,(function(){d=null,k()})))},R=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{p()&&f(R(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(R(t),!1)))},C=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{r=!0,P()})))};n=!0,E.seek((t=>{p()&&(w=Ut(),t?(c=t,!a(e)||t.startTS>e?D(t):(h=t,k())):$())}),e),t.cachedHeader?C(t.cachedHeader):m(t.headerUrl,C,(()=>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=Ut();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(n&&t>a&&Vt(r)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=Ut();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=Ft(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;Ot(e).then((e=>{e||t?.()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return t?.length?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var zt;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(zt||(zt={}));const Qt=[zt.PAUSED,zt.PLAYING,zt.READY],Wt=[zt.PAUSED,zt.PLAYING,zt.READY];class jt{subscription=new i;video;videoState=new Y(zt.STOPPED);dash;representations$=new t([]);textTracksManager=new ft;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new St;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const e=e=>{t.output.error$.next({id:'DashLiveProvider',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(Ct(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Tt(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===zt.READY&&this.videoState.setState(zt.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(zt.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===I.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(zt.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(f({zeroTime:this.zeroTime$.pipe(b(s)),position:i.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(ct(this.video,this.params.desiredState.isLooped,e)).add(lt(this.video,this.params.desiredState.volume,i.volumeState$,e)).add(i.volumeState$.subscribe(this.params.output.volume$,e)).add(pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,e)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&U[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case zt.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case zt.MANIFEST_READY:case zt.READY:break;case zt.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case zt.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return 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 Yt({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){const t=this.representations$.getValue(),e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s(e)?e:_t(t.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.id,r=t.find((({track:t})=>t.id===a))?.representation;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(M(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=Mt(t.name)??H(t.video),a=t.bitrate/1e3,r={...t.video};if(!s)continue;const n={id:e,quality:s,bitrate:a,size:r};i.push({track:n,representation:t})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map((({track:t})=>t))),this.videoState.getTransition()?.to===zt.MANIFEST_READY&&this.videoState.setState(zt.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=this.representations$.getValue().find((({representation:t})=>t===e))?.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e){if(Wt.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;s(t)&&this.setVideoTrack(t);const e=this.params.desiredState.autoVideoTrackSwitching.getTransition();e&&this.setAutoQuality(e.to)}if(a?.to!==P.PAUSED&&r.state===I.Requested&&Qt.includes(t))this.seek(r.position-this.liveOffset.getTotalPausedTime());else switch(t){case zt.STOPPED:return this.videoState.startTransitionTo(zt.MANIFEST_READY),void this.dash.attachSource(M(this.params.source.url));case zt.MANIFEST_READY:this.videoState.startTransitionTo(zt.READY),this.prepare();break;case zt.READY:return void(i===P.PAUSED?this.videoState.setState(zt.PAUSED):i===P.PLAYING&&(this.videoState.startTransitionTo(zt.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(zt.PAUSED)}))));case zt.PLAYING:return void(i===P.PAUSED&&(this.videoState.startTransitionTo(zt.PAUSED),this.liveOffset.pause(),this.dash.pause()));case zt.PAUSED:return void(i===P.PLAYING&&(this.videoState.startTransitionTo(zt.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(zt.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return n(t)}}}else t!==zt.STOPPED&&(this.videoState.startTransitionTo(zt.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(zt.STOPPED))}}var Jt=t=>{const e=t.get('X-Delivery-Type'),i=t.get('X-Reused');return{type:null===e?C.HTTP1:e??void 0,reused:null===i?void 0:{1:!0,0:!1}[i]??void 0}},Xt=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)};class Kt{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(t,e=[],i,s,a,r){this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(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 Zt{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(t){this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),e?.()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,c=0;const l=t=>{s(Zt._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=dt(p)),this._lastXhr=new Kt(p,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),a?.()}),(t=>{if(t.length-o>n&&l(t),0===u)return void(u=Date.now());c=t.length-h;const e=Date.now()-u;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,h=t.length,u=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),t?.()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Zt._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class te{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(t){this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=t.onDashCallback??(()=>{}),this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===i?.[1]?-1:1;e(i?.[2],s),e(i?.[3],s),e(i?.[4],s),e(i?.[5],s);return 3600*e(i?.[6],s)+60*e(i?.[7],s)+e(i?.[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=dt(i)),new Kt(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{const s=t.getElementsByTagName('SegmentBase')[0],o=s&&a(s,'indexRange').split('-'),d=s&&s.getElementsByTagName('Initialization')[0],h=d&&a(d,'range').split('-');if(!h||!o){const e=t.parentElement;if('text'===e?.getAttribute('contentType')){const s=t.getAttribute('id')??void 0,a=(i?i+'/':'')+t.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=e.getAttribute('lang')??void 0;a&&n.push({id:s,url:a,language:r})}return}const u=Number(t.attributes.getNamedItem('bandwidth')?.value),c=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=t.attributes.getNamedItem('frameRate')?.value??void 0;l=p?Et(p):void 0,r.push({width:Number(t.attributes.getNamedItem('width')?.value),height:Number(t.attributes.getNamedItem('height')?.value),bandwidth:u,baseURL:c,failoverHosts:e,indexFrom:Number(o[0]),indexTo:Number(o[1]),initFrom:Number(h[0]),initTo:Number(h[1]),codecs:t.attributes.getNamedItem('codecs')?.value??void 0,mimeType:t.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*u/8,bufferLength:.1,name:t.attributes.getNamedItem('okQuality')?.value??void 0,id:t.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let n=a.getUint32(s,!1),o=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&a.getUint32(s,!1)),i=n+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/r,toTime:i/r,fromOffset:o,toOffset:e-1}),o=e,n=i}const h=t.refs[t.refs.length-1];h.toTime-h.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let r;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.to-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.to&&(a=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new Zt({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const a=this._findRef(e);if(a){if(i){this._isLastRef(a)&&e>=a.toTime&&(e=a.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:a.fromTime}this._appendVector[String(a.fromTime)]=t,this._stream.load(t,a.fromOffset,a.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const a=.1;if(s.toTime<i.to+a){const e=this._findRef(s.toTime);e&&e.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!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 ee;!function(t){t.STOPPED='stopped',t.MANIFEST_LOADED='manifest-loaded',t.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',t.METADATA_LOADED='metadata-loaded',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ee||(ee={}));const ie=[ee.PAUSED,ee.PLAYING];class se{videoState=new Y(ee.STOPPED);subscription=new i;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new ft;elementSize$=new t(void 0);dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),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(Ct(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new vt(this.video),this.dash=new te({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i})},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=Tt(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!==I.Applying)&&(this.videoState.getState()===ee.PLAYING||this.videoState.getState()===ee.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,e.playbackRate,d.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),l(It(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(ee.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(ee.PLAYING),O(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(ee.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=Xt(this.video.buffered,1e3*this.video.currentTime),s=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(i/s,1);h=_t(e.map((({track:t})=>t)),{container: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(f({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(b((t=>t.to===ee.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(b(s))}).pipe(g()).subscribe((()=>this.videoState.setState(ee.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(b(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=Xt(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Ct(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(g(),S(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(b(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&&Mt(i.name))??H(i),a=i.bandwidth/1e3,r={width:i.width,height:i.height},n=i.fps;if(!s)continue;const o={id:t,quality:s,bitrate:a,size:r,fps:n};e.push({track:o,representation:i})}this.representations$.next(e),this.params.output.availableVideoTracks$.next(e.map((({track:t})=>t))),this.videoState.setState(ee.MANIFEST_LOADED)};handleRepresentationPlay=t=>{const e=this.representations$.getValue().find((({representation:e})=>e===t))?.track;if(e){this.params.output.currentVideoTrack$.next(e);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(e.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return 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(){Ot(this.video).then((t=>{t||(this.videoState.setState(ee.PAUSED),O(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===I.Requested&&ie.includes(t)&&this.seek(a.position,a.forcePrecise),t){case ee.STOPPED:return this.videoState.startTransitionTo(ee.MANIFEST_LOADED),void this.prepare();case ee.MANIFEST_LOADED:return void this.videoState.startTransitionTo(ee.INITIAL_REPRESENTATION_SELECTED);case ee.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(ee.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case ee.METADATA_LOADED:return this.videoState.startTransitionTo(ee.READY),void this.dash.updateRefsForCurrentTime();case ee.READY:return void(i===P.PAUSED?(this.videoState.setState(ee.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()));case ee.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):s?.to===P.PLAYING&&O(this.params.desiredState.playbackState,P.PLAYING));case ee.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):s?.to===P.PAUSED&&O(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ee.STOPPED),O(this.params.desiredState.playbackState,P.STOPPED,!0))}}var ae,re,ne,oe,de;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(ae||(ae={})),function(t){t.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',t.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(re||(re={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(ne||(ne={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(oe||(oe={})),function(t){t.MP4='mp4',t.WEBM='webm'}(de||(de={}));var he=(t,e)=>{for(let i=0;i<t.length;i++){if(1e3*t.start(i)<=e&&1e3*t.end(i)>e)return!0}return!1};const ue='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;let ce=!1;try{ce=bt()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??'',10)<16}catch(t){console.error(t)}class le{bufferFull$=new e;error$=new e;buffer;queue=[];currentTask=null;destroyed=!1;constructor(t){this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const a={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(a),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=ce&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}completeTask=()=>{try{if(this.currentTask){const t=this.currentTask.signal?.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',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,me=t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(pe||(pe={}));class fe{throughputEstimator;requestQuic;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new et;subscription=new i;constructor({throughputEstimator:t,requestQuic:e}){this.throughputEstimator=t,this.requestQuic=e}onHeadersReceived(t){const{type:e,reused:i}=Jt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest=T(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=dt(e));const i=yield tt(e,{signal:this.abortAllController.signal}).catch(ge);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=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=dt(u));let l=this.abortAllController.signal;if(d){const t=new et;if(this.subscription.add(o(r(this.abortAllController.signal,'abort'),r(d,'abort')).subscribe((()=>{try{t.abort()}catch(t){ge(t)}}))),this.abortAllController.signal.aborted||d.aborted)try{t.abort()}catch(t){ge(t)}l=t.signal}const p=v(),m=yield tt(u,{priority:a,headers:c,signal:l}).catch(ge),f=v();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,v()-f),s?.(new DataView(t),t.byteLength),t}if(!s&&!h)return m.arrayBuffer();const[S,b]=m.body.tee(),y=S.getReader();h&&this.throughputEstimator?.trackStream(b);let E=0;const w=new ArrayBuffer(g),$=new Uint8Array(w),k=new DataView(w);let A=!1;const P=t=>{A=!0,ge(t)},R=T(l,async function*({done:t,value:e}){0===E&&this.lastRequestFirstBytes$.next(v()-p),l.aborted||(t?s?.(k,E):e&&($.set(e,E),E+=e.byteLength,s?.(k,E),yield y?.read().then(R,P)))}.bind(this));return yield y?.read().then(R,P),A?null:w}.bind(this));async fetchRepresentation(t,e,i='auto'){const{type:s}=t;switch(s){case ne.BYTE_RANGE:return await this.fetchByteRangeRepresentation(t,e,i)??null;case ne.TEMPLATE:return await this.fetchTemplateRepresentation(t,i)??null;default:n(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=T(this.abortAllController.signal,async function*(t,e,i){if(t.type!==ne.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,n,o=s,d=a,h=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,h=a+1===r,h&&(o=Math.min(r,s),d=Math.max(n,a))),o=Math.min(o,0);const u=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!u)return null;const c=new DataView(u,s-o,a-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(h&&void 0!==r&&void 0!==n)p=new DataView(u,r-o,n-r+1);else{const s=e.getIndexRange(l);if(s){const e=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,l);return{dataView:new DataView(u),segments:m}}.bind(this));fetchTemplateRepresentation=T(this.abortAllController.signal,async function*(t,e){if(t.type!==ne.TEMPLATE)return null;const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield this.fetch(i,{priority:e,measureThroughput:!1});if(!s)return null;return{segments:t.segments.map((t=>({...t,status:oe.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this))}const ge=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Se=new TextDecoder('ascii'),be=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=Se.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},ve={validateData:t=>'ftyp'===Se.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=be(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),d=4294967295&a();let h=n/r*1e3,u=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=a(),e=t>>>31,s=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;i.push({status:oe.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=be(a);if(s||='mdat'===i.id,!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var ye,Te;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(ye||(ye={})),function(t){t.SignedInteger='int',t.UnsignedInteger='uint',t.Float='float',t.String='string',t.UTF8='utf8',t.Date='date',t.Master='master',t.Binary='binary'}(Te||(Te={}));const Ee={[ye.EBML]:{type:Te.Master},[ye.EBMLVersion]:{type:Te.UnsignedInteger},[ye.EBMLReadVersion]:{type:Te.UnsignedInteger},[ye.EBMLMaxIDLength]:{type:Te.UnsignedInteger},[ye.EBMLMaxSizeLength]:{type:Te.UnsignedInteger},[ye.DocType]:{type:Te.String},[ye.DocTypeVersion]:{type:Te.UnsignedInteger},[ye.DocTypeReadVersion]:{type:Te.UnsignedInteger},[ye.Void]:{type:Te.Binary},[ye.Segment]:{type:Te.Master},[ye.SeekHead]:{type:Te.Master},[ye.Seek]:{type:Te.Master},[ye.SeekID]:{type:Te.Binary},[ye.SeekPosition]:{type:Te.UnsignedInteger},[ye.Info]:{type:Te.Master},[ye.TimestampScale]:{type:Te.UnsignedInteger},[ye.Duration]:{type:Te.Float},[ye.Tracks]:{type:Te.Master},[ye.Chapters]:{type:Te.Master},[ye.Cluster]:{type:Te.Master},[ye.Timestamp]:{type:Te.UnsignedInteger},[ye.SilentTracks]:{type:Te.Master},[ye.SilentTrackNumber]:{type:Te.UnsignedInteger},[ye.Position]:{type:Te.UnsignedInteger},[ye.PrevSize]:{type:Te.UnsignedInteger},[ye.SimpleBlock]:{type:Te.Binary},[ye.BlockGroup]:{type:Te.Master},[ye.EncryptedBlock]:{type:Te.Binary},[ye.Attachments]:{type:Te.Master},[ye.Tags]:{type:Te.Master},[ye.Cues]:{type:Te.Master},[ye.CuePoint]:{type:Te.Master},[ye.CueTime]:{type:Te.UnsignedInteger},[ye.CueTrackPositions]:{type:Te.Master},[ye.CueTrack]:{type:Te.UnsignedInteger},[ye.CueClusterPosition]:{type:Te.UnsignedInteger},[ye.CueRelativePosition]:{type:Te.UnsignedInteger},[ye.CueDuration]:{type:Te.UnsignedInteger},[ye.CueBlockNumber]:{type:Te.UnsignedInteger},[ye.CueCodecState]:{type:Te.UnsignedInteger},[ye.CueReference]:{type:Te.Master},[ye.CueRefTime]:{type:Te.UnsignedInteger}},we=t=>{const e=t.getUint8(0);let i=0;128&e?i=1:64&e?i=2:32&e?i=3:16&e&&(i=4);const s=$e(t,i),a=s in Ee,r=a?Ee[s].type:Te.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),h=((n&255>>o)<<8*(o-1))+$e(d),u=i+o;let c;return c=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:u,tagSize:u+h,value:c,valueSize:h}},$e=(t,e=t.byteLength)=>{switch(e){case 1:return t.getUint8(0);case 2:return t.getUint16(0);case 3:return t.getUint16(0)<<8|t.getUint8(2);case 4:return t.getUint32(0);case 5:return t.getUint32(0)<<8|t.getUint8(4);case 6:return t.getUint32(0)<<16|t.getUint16(4);case 7:return t.getUint32(0)<<32|t.getUint16(4)<<8|t.getUint8(6);case 8:return t.getUint32(0)<<32|t.getUint32(4)}return 0},ke=(t,e)=>{switch(e){case Te.SignedInteger:return t.getInt8(0);case Te.UnsignedInteger:return $e(t);case Te.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Te.String:return new TextDecoder('ascii').decode(t);case Te.UTF8:return new TextDecoder('utf-8').decode(t);case Te.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Te.Master:case Te.Binary:return t;default:n(e)}},Ae=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=we(s);if(!e(a))return;a.type===Te.Master&&Ae(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},Pe=[ye.Info,ye.SeekHead,ye.Tracks,ye.Chapters,ye.Cluster,ye.Cues,ye.Attachments,ye.Tags],Re=[ye.Timestamp,ye.SilentTracks,ye.SilentTrackNumber,ye.Position,ye.PrevSize,ye.SimpleBlock,ye.BlockGroup,ye.EncryptedBlock],De={validateData:t=>{if(t.getUint32(0)!==ye.EBML)return!1;let e,i,s;const a=we(t);return Ae(a.value,(({tag:t,type:a,value:r})=>(t===ye.EBMLReadVersion?e=ke(r,a):t===ye.DocType?i=ke(r,a):t===ye.DocTypeReadVersion&&(s=ke(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,a,r,n,o=!1,d=!1,h=!1;return Ae(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===ye.SeekID){const t=ke(c,u);n=$e(t)}else t!==ye.SeekPosition&&(n=void 0);return t===ye.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===ye.Info?o=!0:t===ye.SeekHead?d=!0:t===ye.TimestampScale?s=ke(c,u):t===ye.Duration?a=ke(c,u):t===ye.SeekPosition&&n===ye.Cues?r=ke(c,u):o&&d&&Pe.includes(t)&&(h=!0),!h})),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 Ae(t,(({tag:t,type:e,value:s})=>{switch(t){case ye.Cues:i=!0;break;case ye.CuePoint:o&&r(o)&&n.push(o),o={};break;case ye.CueTime:o&&(o.time=ke(s,e));break;case ye.CueTrackPositions:break;case ye.CueClusterPosition:o&&(o.position=ke(s,e));break;default:i&&Pe.includes(t)&&(a=!0)}return!(i&&a)})),o&&r(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:a}=t,r=n[i+1];return{status:oe.NONE,time:{from:s,to:r?r.time:e.segmentDuration},byte:{from:e.segmentStart+a,to:r?e.segmentStart+r.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Ae(t,(s=>s.tag===ye.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Re.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||=[ye.SimpleBlock,ye.BlockGroup,ye.EncryptedBlock].includes(s.tag)),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class _e{onLastSegment$=new t(!1);fullyBuffered$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;gaps=[];subscription=new i;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new et;destroyAbortController=new et;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;constructor(t,e,i,s,{fetcher:a,tuning:r,getCurrentPosition:o}){switch(this.fetcher=a,this.tuning=r,this.forwardBufferTarget=r.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case de.MP4:this.containerParser=ve;break;case de.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=>{if(!this.sourceBuffer)return;const e=Math.min(this.bufferLimit,me(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield this.loadInit(e,'high',!0);const i=this.initData.get(e.id),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 et,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=Xt(this.sourceBuffer.buffered,t),a=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(r=a)}if(isFinite(this.bufferLimit)&&me(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),s&&s.status!==oe.NONE))return;let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,e.segmentReference.type,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===oe.FED&&!n.length&&Xt(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=i.at(-1);o&&o.status===oe.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){const e=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!e)return;const i=this.segments.get(e);if(!i)return;return i.find((e=>e.time.from<=t&&e.time.to>=t))?.time.from??void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===oe.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==ne.BYTE_RANGE)return t.slice(s,s+1);const a=t;let r=0;const n=[];for(let t=s;t<a.length&&r<=this.tuning.dash.segmentRequestSize;t++){const e=a[t];if(r+=e.byte.to+1-e.byte.from,e.status!==oe.NONE&&e.status!==oe.PARTIALLY_EJECTED)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,a,r=t;const{type:o}=e.segmentReference;switch(o){case ne.BYTE_RANGE:s=e.segmentReference.url,a={from:t.at(0).byte.from,to:t.at(-1).byte.to};break;case ne.TEMPLATE:{const i=t.at(0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),r=[i];break}default:n(o)}for(const t of r)t.status=oe.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes: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=Xt(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=oe.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const i of this.representations.values())if(i.id!==e)for(const e of this.segments.get(i.id)??[])e.status===oe.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=oe.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,h=t.byteLength;for(const o of this.activeSegments){const{segment:u}=o,c=d===ne.BYTE_RANGE,l=c?u.byte.to-u.byte.from+1:h;if(o.representationId!==e)continue;if(!(!c||u.byte.from>=i&&u.byte.to<i+t.byteLength))continue;if(a.aborted){r(o);continue}const p=c?u.byte.from-i:0,m=p<s,f=(c?u.byte.to-i:t.byteLength)<=s;if(u.status===oe.DOWNLOADING&&m&&f){u.status=oe.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,l);this.sourceBufferTaskQueue.append(e,a).then((t=>t&&!a.aborted?n(o):r(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(l,s-p),o.loadedBytes>o.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),i=o.loadedBytes===l?e:this.containerParser.parseFeedableSegmentChunk(e);i?.byteLength&&(u.status=oe.PARTIALLY_FED,o.feedingBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,a).then((t=>{if(a.aborted)r(o);else if(t)o.fedBytes+=i.byteLength,o.fedBytes===l&&n(o);else{if(o.feedingBytes<l)return;r(o)}})))}}}abortSegment(t){t.status===oe.PARTIALLY_FED||t.status===oe.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=oe.NONE)),t.status=oe.PARTIALLY_EJECTED):t.status=oe.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const a=s instanceof Promise;e||=a,null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=ue((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,e='auto',i=!1){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',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===oe.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===oe.FED&&d(a)}}if(o=isFinite(r)&&isFinite(n),!o)for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=1e3*this.sourceBuffer.buffered.end(t);for(const t of i)if(t.status===oe.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(s)){r=e,n=s;break}}return o=isFinite(r)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(r,n)}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),e=t instanceof ArrayBuffer?t:void 0;this.sourceBufferTaskQueue.abort(e)}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ue((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',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=Math.round(1e3*this.sourceBuffer.buffered.start(e)),s=Math.round(1e3*this.sourceBuffer.buffered.end(e));t.push({from:i,to:s})}for(const e of this.segments.values())for(const i of e){const{status:e}=i;if(e!==oe.FED&&e!==oe.PARTIALLY_EJECTED)continue;const s=Math.round(i.time.from),a=Math.round(i.time.to),r=t.some((t=>t.from<=s&&t.to>=a)),n=t.some((t=>s>t.from&&s<t.to||a>t.from&&a<t.to));r||(i.status=n?oe.PARTIALLY_EJECTED:oe.NONE)}}}const Ce=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 xe,Be;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(xe||(xe={}));class Ne{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new i;fetcher;state$=new Y(xe.NONE);currentVideoRepresentation$=new t(void 0);error$=new e;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);forceEnded$=new e;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new et;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new fe({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=T(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(xe.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',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=Ce(d);else if(h){const t=Ce(h);s(t)&&(o=t)}let u=0;const c=a.getAttribute('profiles')?.split(',')??[],l=c.includes(re.WEBM_AS_IN_FFMPEG)||c.includes(re.WEBM_AS_IN_SPEC)?de.WEBM:de.MP4;for(const t of n){const s=t.getAttribute('mimeType'),a=t.getAttribute('codecs'),r=t.getAttribute('contentType')??s?.split('/')[0],n=t.getAttribute('profiles')?.split(',')??[],d=t.querySelectorAll('Representation');if('text'!==r)for(const h of d){const d=h.getAttribute('mimeType')??s,l=h.getAttribute('codecs')??a??'',p=h.getAttribute('contentType')??d?.split('/')[0]??r,m=t.getAttribute('profiles')?.split(',')??[],f=parseInt(h.getAttribute('width')??'',10),g=parseInt(h.getAttribute('height')??'',10),S=parseInt(h.getAttribute('bandwidth')??'',10)/1e3,b=h.getAttribute('frameRate')??'',v=h.getAttribute('quality')??void 0,y=b?Et(b):void 0,T=`${h.getAttribute('id')??(u++).toString(10)}@${'video'===p?`${g}p`:'audio'===p?`${S}Kbps`:l}`,E=h.querySelector('BaseURL')?.textContent?.trim()??'',w=new URL(E,e).toString(),$=[...c,...n,...m];let k;const A=h.querySelector('SegmentBase'),P=h.querySelector('SegmentTemplate');if(A){const t=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[r,n]=a?a.split('-').map((t=>parseInt(t,10))):[],o=a?{from:r,to:n}:void 0;k={type:ne.BYTE_RANGE,url:w,initRange:s,indexRange:o}}else{if(!P)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:h.getAttribute('id')??void 0,bandwidth:h.getAttribute('bandwidth')??void 0},e=parseInt(P.getAttribute('timescale')??'',10),i=P.getAttribute('initialization')??'',s=P.getAttribute('media'),a=parseInt(P.getAttribute('startNumber')??'',10)??1,r=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:ne.TEMPLATE,baseUrl:w,initUrl:r,segments:o}}}if(!p||!d)continue;const R={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[p];R&&i[R].push({id:T,kind:R,segmentReference:k,profiles:$,duration:o,bitrate:S,mime:d,codecs:l,width:f,height:g,fps:y,quality:v})}}return{duration:o,container:l,representations:i}})(i??'',e)}catch(t){this.error$.next({id:'ManifestParsing',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(xe.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(xe.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new _e(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new _e(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const 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$,f({allBuffersFull:a,someBufferEnded:n}).pipe(b((({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(xe.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&&he(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this));async switchRepresentation(t,e){return{[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[t]?.switchTo(e)}seek(t,e){let i;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),he(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(xe.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager?.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager?.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=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'}(Be||(Be={}));const Me=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?Mt(r):void 0)??H({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Oe=(t,e,i)=>{const s=e.indexOf(i);return t.at(Math.round(t.length*s/e.length))??t.at(-1)};class Ue{subscription=new i;videoState=new Y(Be.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(Ct(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ne({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=Tt(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(b(s),g(),S(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(ct(this.video,e.isLooped,a)),this.subscription.add(lt(this.video,e.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(pt(this.video,e.playbackRate,i.playbackRateState$,a)),n(It(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Be.PLAYING),O(e.playbackState,P.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(Be.PAUSED),O(e.playbackState,P.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Be.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(b((({to:t})=>t===xe.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Be.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===xe.NONE||!this.videoTracks.length)return;const a=i===xe.MANIFEST_LOADED&&!s,r=i===xe.REPRESENTATION_SELECTED&&!s,n=e.autoVideoTrackSwitching.getState(),o=e.videoTrack.getState(),h=this.videoTracks.find((({track:{id:t}})=>t===o))?.track,u=t.currentVideoTrack$.getValue(),c=Xt(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(ae.VIDEO,t.id).catch(d),e&&this.player.switchRepresentation(ae.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=Me(t);if(s){this.videoTracks.push({track:s,representation:t});const a=Oe(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===I.Requested&&i?.to!==P.PAUSED&&t!==Be.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===Be.STOPPED)return this.videoState.startTransitionTo(Be.READY),void this.prepare();switch(t){case Be.READY:return void(e===P.PAUSED?(this.videoState.setState(Be.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Be.PLAYING),this.playIfAllowed()));case Be.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Be.PAUSED),this.video.pause()):i?.to===P.PLAYING&&O(this.params.desiredState.playbackState,P.PLAYING));case Be.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Be.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&O(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==Be.STOPPED&&(this.videoState.startTransitionTo(Be.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(Be.STOPPED),O(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(){Ot(this.video).then((t=>{t||(this.videoState.setState(Be.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Ve={};var qe;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(qe||(qe={}));const Fe=(t,e)=>new y((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class He{subscription=new i;videoState=new Y(qe.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(Ct(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||(Ve.Hls=e.default,Ve.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){l(Ve.Hls,'hls.js not loaded'),this.hls=new Ve.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(qe.STOPPED)}subscribe(){l(Ve.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=Tt(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(ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(Fe(this.hls,Ve.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(qe.PLAYING),O(t.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(qe.PAUSED),O(t.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===qe.READY&&this.videoState.setState(qe.READY),this.videoState.getState()===qe.PLAYING&&this.playIfAllowed()}),i)),n(Fe(this.hls,Ve.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=Mt(e.attrs.QUALITY??'')??H({width:s,height:a});if(!r)return t;const n=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,o={id:i.toString(),quality:r,bitrate:e.bitrate/1e3,size:{width:s,height:a},fps:n};return this.trackLevels.set(i,{track:o,level:e}),t.push(o),t}),[])))),e.availableVideoTracks$),n(Fe(this.hls,Ve.Events.LEVEL_LOADING).pipe(h((({url:t})=>Ct(t)))),e.hostname$),this.subscription.add(ut(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const d=t=>Array.from(this.trackLevels.values()).find((({level:e})=>e===t))?.track,c=Fe(this.hls,Ve.Events.LEVEL_SWITCHED).pipe(h((({level:t})=>d(this.hls.levels[t]))));c.pipe(b(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(ut(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!==qe.INITIALIZING)switch(i?.to!==P.PAUSED&&s.state===I.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case qe.STOPPED:break;case qe.READY:case qe.PLAYING:case qe.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case qe.PLAYING:break;case qe.STOPPED:this.prepare();break;case qe.READY:case qe.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case qe.PAUSED:break;case qe.STOPPED:this.prepare();break;case qe.READY:this.videoState.setState(qe.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED);break;case qe.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}};prepare(){this.videoState.startTransitionTo(qe.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(qe.PLAYING);await Ot(this.video)||(this.videoState.setState(qe.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(qe.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(qe.STOPPED),O(this.params.desiredState.playbackState,P.STOPPED,!0)}}var Ge=async t=>{const e=await tt(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0};const Ye=t=>{let e=null;if(t.QUALITY&&(e=Mt(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=H({width:i,height:s})}return e??null},ze=async(t,e=t)=>{const i=await tt(t),s=(await i.text()).split('\n'),a=[];for(let t=0;t<s.length;t++){const i=s[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!i)continue;const r=Object.fromEntries(i[1].split(',').map((t=>t.split('=')))),n=r.QUALITY??`stream-${r.BANDWIDTH}`,o=Ye(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let u;if(r.RESOLUTION){const[t,e]=r.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(u={width:t,height:e})}const c=new URL(s[++t],e).toString();o&&a.push({id:n,quality:o,url:c,bandwidth:d,size:u,fps:h})}return a};var Qe,We,je;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Qe||(Qe={}));class Je{subscription=new i;videoState=new Y(Qe.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);maxSeekBackTime$;liveOffset=new St;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:N.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),ze(M(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(Ct(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=Tt(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(lt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Qe.PLAYING),O(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Qe.PAUSED),O(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Qe.READY&&this.videoState.setState(Qe.READY),this.videoState.getState()===Qe.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(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(Ct(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Qe.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===I.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(f({startTime:this.manifestStartTime$.pipe(b(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=M(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),Ge(e).then((t=>{if(a(t)){const t=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(a(t)||!isFinite(t))try{tt(e).then((t=>t.text())).then((t=>{const i=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(t)?.[1];if(i){const t=new URL(i,e).toString();Ge(t).then((t=>{a(t)||this.maxSeekBackTime$.next(t)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Ot(this.video).then((t=>{t||(this.videoState.setState(Qe.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Qe.STOPPED&&(this.videoState.startTransitionTo(Qe.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Qe.STOPPED),O(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===Qe.STOPPED)return this.videoState.startTransitionTo(Qe.READY),void this.prepare();if(s||a){const t=this.videoState.getState();return this.videoState.setState(Qe.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(r.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if(i?.to!==P.PAUSED&&r.state===I.Requested)return this.videoState.startTransitionTo(Qe.READY),this.seek(r.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Qe.READY:return void(e===P.PAUSED?(this.videoState.setState(Qe.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Qe.PLAYING),this.playIfAllowed()));case Qe.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Qe.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===P.PLAYING&&O(this.params.desiredState.playbackState,P.PLAYING));case Qe.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Qe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):i?.to===P.PAUSED&&(O(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Qe.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'}(We||(We={}));class Xe{subscription=new i;videoState=new Y(We.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video);const e={id:'master',quality:N.INVARIANT,url:this.params.source.url};this.manifests$.next([e]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Ct(this.params.source.url)),ze(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=Tt(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(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(We.PLAYING),O(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(We.PAUSED),O(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===We.READY&&this.videoState.setState(We.READY),this.videoState.getState()===We.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(Ct(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===We.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===I.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(){Ot(this.video).then((t=>{t||(this.videoState.setState(We.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==We.STOPPED&&(this.videoState.startTransitionTo(We.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(We.STOPPED),O(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===We.STOPPED)return this.videoState.startTransitionTo(We.READY),void this.prepare();if(s||a){const t=this.videoState.getState();this.videoState.setState(We.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(r.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:1e3*e,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&r.state===I.Requested&&this.seek(r.position),t){case We.READY:return void(e===P.PAUSED?(this.videoState.setState(We.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(We.PLAYING),this.playIfAllowed()));case We.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(We.PAUSED),this.video.pause()):i?.to===P.PLAYING&&O(this.params.desiredState.playbackState,P.PLAYING));case We.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(We.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&O(this.params.desiredState.playbackState,P.PAUSED));case We.CHANGING_MANIFEST:break;default:return n(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(je||(je={}));class Ke{subscription=new i;videoState=new Y(je.STOPPED);video;trackUrls={};params;textTracksManager=new ft;constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=Tt(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(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(je.PLAYING),O(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(je.PAUSED),O(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===je.READY&&this.videoState.setState(je.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&s(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===je.PLAYING&&this.playIfAllowed()}),i)),this.textTracksManager.connect(this.video,e,t);const 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=dt(e)),this.video.setAttribute('src',e),this.video.load(),this.params.output.hostname$.next(Ct(e))}playIfAllowed(){Ot(this.video).then((t=>{t||(this.videoState.setState(je.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==je.STOPPED&&(this.videoState.startTransitionTo(je.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(je.STOPPED),O(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(t===je.STOPPED)return this.videoState.startTransitionTo(je.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(a.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:1e3*t,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&a.state===I.Requested&&this.seek(a.position),t){case je.READY:return void(e===P.PAUSED?(this.videoState.setState(je.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(je.PLAYING),this.playIfAllowed()));case je.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(je.PAUSED),this.video.pause()):i?.to===P.PLAYING&&O(this.params.desiredState.playbackState,P.PLAYING));case je.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(je.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&O(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}}const Ze=['stun:videostun.mycdn.me:80'],ti=()=>null;class ei{options;ws=null;peerConnection=null;serverUrl='';streamKey='';stream=null;signalingType='JOIN';retryTimeout;retryCount=0;externalStartCallback=ti;externalStopCallback=ti;externalErrorCallback=ti;constructor(t,e){this.options=this.normalizeOptions(e);const i=t.split('/');this.serverUrl=i.slice(0,i.length-1).join('/'),this.streamKey=i[i.length-1]}onStart(t){try{this.externalStartCallback=t}catch(t){this.handleSystemError(t)}}onStop(t){try{this.externalStopCallback=t}catch(t){this.handleSystemError(t)}}onError(t){try{this.externalErrorCallback=t}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(t){this.handleSystemError(t)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(t){try{if(!this.ws)return;this.ws=null,t.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(t){try{this.externalErrorCallback(new Error(t.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(t){try{const e=this.parseMessage(t.data);switch(e.type){case'JOIN':case'CALL_JOIN':this.handleJoinMessage(e);break;case'UPDATE':this.handleUpdateMessage(e);break;case'STATUS':this.handleStatusMessage(e)}}catch(t){this.handleRTCError(t)}}handleJoinMessage(t){switch(t.inviteType){case'ANSWER':this.handleAnswer(t.sdp);break;case'CANDIDATE':this.handleCandidate(t.candidate)}}handleStatusMessage(t){switch(t.status){case'UNPUBLISHED':this.handleUnpublished()}}async handleUpdateMessage(t){try{const e=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(e),this.handleAnswer(t.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const t={iceServers:[{urls:Ze}]};this.peerConnection=new RTCPeerConnection(t),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const e=await this.createOffer();await this.peerConnection.setLocalDescription(e),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:e.sdp,callSupport:!1})}catch(t){this.handleRTCError(t)}}async handleAnswer(t){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:t}))}catch(t){this.handleRTCError(t)}}async handleCandidate(t){if(t)try{this.peerConnection&&await this.peerConnection.addIceCandidate(t)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(t){this.handleRTCError(t)}}handleSystemError(t){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',message:t.message})}async onPeerConnectionStream(t){const e=t.streams[0];this.stream&&this.stream.id===e.id||(this.stream=e,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(t){t.candidate&&this.send({type:this.signalingType,inviteType:'CANDIDATE',candidate:t.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const t=this.peerConnection.iceConnectionState;['failed','closed'].indexOf(t)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const t=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}),e=t.sdp||'';if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(e))throw new Error('No h264 codec support error');return t}handleRTCError(t){try{this.externalErrorCallback(t||new Error('RTC connection error'))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error('Network error'))}catch(t){this.handleSystemError(t)}}send(t){this.ws&&this.ws.send(JSON.stringify(t))}parseMessage(t){try{return JSON.parse(t)}catch(t){throw new Error('Can not parse socket message')}}closeConnections(){const t=this.ws;t&&(this.ws=null,t.close(1e3)),this.removePeerConnection()}removePeerConnection(){let t=this.peerConnection;t&&(this.peerConnection=null,t.close(),t.ontrack=null,t.onicecandidate=null,t.oniceconnectionstatechange=null,t=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),1e3)}normalizeOptions(t={}){const e={stunServerList:Ze,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var ii;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ii||(ii={}));class si{subscription;params;log;video;videoState=new Y(ii.STOPPED);liveStreamClient;maxSeekBackTime$=new t(0);constructor(t){this.subscription=new i,this.params=t,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=gt(t.container),this.liveStreamClient=new ei(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'WebRTCLiveProvider',message:'WebRTCLiveProvider 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)}`})}));const s=Tt(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(s.timeUpdate$,t.liveTime$),a(s.ended$,t.endedEvent$),a(s.looped$,t.loopedEvent$),a(s.error$,t.error$),a(s.isBuffering$,t.isBuffering$),a(s.currentBuffer$,t.currentBuffer$),this.subscription.add(s.durationChange$.subscribe((e=>{t.duration$.next(e===1/0?0:e)}))).add(s.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ii.READY&&this.videoState.setState(ii.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(ii.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.videoState.setState(ii.PLAYING)}),i)).add(s.error$.subscribe(t.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(lt(this.video,e.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(t.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe((i=>{switch(i.to){case ii.STOPPED:t.position$.next(0),t.duration$.next(0),e.playbackState.setState(P.STOPPED);break;case ii.READY:break;case ii.PAUSED:e.playbackState.setState(P.PAUSED);break;case ii.PLAYING:e.playbackState.setState(P.PLAYING);break;default:return n(i.to)}}),i)).add(o(e.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,u(['init'])).pipe(p(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i))}onLiveStreamStart(t){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Ct(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:N.INVARIANT}),this.video.srcObject=t,O(this.params.desiredState.playbackState,P.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ii.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(t){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',message:t.message,thrown:t})}playIfAllowed(){Ot(this.video).then((t=>{t||(this.videoState.setState(ii.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==ii.STOPPED&&(this.videoState.startTransitionTo(ii.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ii.STOPPED),O(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition();if(t===ii.STOPPED)return this.videoState.startTransitionTo(ii.READY),void this.prepare();if(s)this.prepare();else switch(t){case ii.READY:return void(e===P.PAUSED?(this.videoState.setState(ii.PAUSED),O(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(ii.PLAYING),this.playIfAllowed()));case ii.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(ii.PAUSED),this.video.pause()):i?.to===P.PLAYING&&O(this.params.desiredState.playbackState,P.PLAYING));case ii.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(ii.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&O(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}}class ai{iterator;current;constructor(t){this.iterator=t[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const ri=bt(),ni=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),oi=document.createElement('video'),di={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(oi.canPlayType?.('application/x-mpegurl')||oi.canPlayType?.('vnd.apple.mpegURL')),webrtc:Boolean(window.RTCPeerConnection)},hi={mp4:Boolean(oi.canPlayType?.('video/mp4')),webm:Boolean(oi.canPlayType?.('video/webm'))},ui={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},ci=(ui.h264||ui.h265)&&ui.aac,li=!ri,pi=di.hls&&hi.mp4&&(ni||ri),mi=Boolean(window.WebSocket);const fi=3e4,gi=18e4,Si=3,bi=100,vi={cacheDuration:12e4},yi={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Ti={maxPausedTime:3e4},Ei={maxPausedTime:3e4};class wi{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 ai(((t,e=!1)=>t.filter((t=>{switch(t){case R.DASH:return di.mse&&hi.mp4&&ci&&li;case R.DASH_SEP:return di.mse&&hi.mp4&&ci;case R.DASH_WEBM:return di.mse&&hi.webm&&ui.vp9&&ui.opus;case R.DASH_LIVE:case R.DASH_ONDEMAND:return di.mse&&hi.mp4&&ci;case R.HLS:case R.HLS_LIVE:case R.HLS_ONDEMAND:return pi||e&&di.mse&&hi.mp4&&ci;case R.MPEG:return hi.mp4;case R.DASH_LIVE_WEBM:return!1;case R.WEB_RTC_LIVE:return di.webrtc&&mi&&ui.h264&&(hi.mp4||hi.webm);default:return n(t)}})))(i.filter((e=>s(t.sources[e]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new ai(t.chromecastFormatsPriority.filter((e=>s(t.sources[e]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),e=this.chooseFormat(t);if(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!==I.None;this.params.desiredState.seekState.setState({state:I.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case D.SCREEN:return this.createScreenProvider(e);case D.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,a=this.providerOutput,r={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case R.DASH:{const i=e[t];return l(i),new se({...r,source:i,config:vi})}case R.DASH_SEP:case R.DASH_WEBM:case R.DASH_ONDEMAND:{const i=e[t];return l(i),this.params.tuning.useDashJs?new Nt({...r,source:i,format:t,config:Ei}):new Ue({...r,source:i})}case R.HLS:case R.HLS_ONDEMAND:{const i=e[t];return l(i),pi||!this.params.tuning.useHlsJs?new Xe({...r,source:i}):new He({...r,source:i})}case R.HLS_LIVE:{const i=e[t];return l(i),new Je({...r,source:i,config:Ti})}case R.MPEG:{const i=e[t];return l(i),new Ke({...r,source:i})}case R.DASH_LIVE:{const i=e[t];return l(i),new jt({...r,source:i,config:yi})}case R.WEB_RTC_LIVE:{const r=e[t];return l(r),new si({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case R.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return 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 Q({connection:n,meta:a,container:i,source:e,format:t,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?D.CHROMECAST:D.SCREEN}chooseFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case D.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.next();case D.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case D.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case D.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return 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:fi,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(b((({type:t})=>void 0!==t)))},new y((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($(bi,{leading:!1,trailing:!0})).subscribe((()=>{const e=Date.now();this.current$.getValue().destination===D.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(t[a])&&e<t[a]+gi?(t=[],this.switchToNextProvider()):(t[a]=e,this.reinitProvider()),a=(a+1)%Si}))),r}}const $i=(t,e,i)=>i*e+(1-i)*t;class ki{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const i=e.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Pt(`raw_${i}`),this.smoothedSeries$=new Pt(`smoothed_${i}`),this.reportedSeries$=new Pt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=(this.pastMeasures[t]-this.smoothed)**2,i++);e/=i;const s=Math.sqrt(e),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=$i(this.slow,t,this.params.emaAlphaSlow),this.fast=$i(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 Ai;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Ai||(Ai={}));const Pi=new Map;let Ri=Ai.RUNTIME;const Di=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Di,'test'),localStorage.removeItem(Di),Ri=Ai.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Di),Ri=Ai.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Ri=Ai.RUNTIME}}})();const _i=(t,e)=>{switch(Ri){case Ai.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ai.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ai.RUNTIME:return void Pi.set(t,e);default:n(Ri)}},Ci=window.navigator.connection,Ii=()=>{const t=Ci?.downlink;if(s(t)&&10!==t)return 1e3*t},Li=()=>{const t=Ci?.rtt;if(s(t)&&3e3!==t)return t},xi=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Bi{throughput;rtt;subscription=new i;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=Bi.load('one_video_throughput')||(e.useBrowserEstimation?Ii():void 0)||5e3,a=Bi.load('one_video_rtt')??(e.useBrowserEstimation?Li():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(xi(i,a,e.rttPenaltyRequestSize)),this.throughput=new ki({initial:i,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new ki({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=Ii();t&&this.throughput.next(t);const e=Li();s(e)&&this.rtt.next(e)};Ci&&'onchange'in Ci&&this.subscription.add(r(Ci,'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(f({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(h((({throughput:t,rtt:i})=>xi(t,i,e.rttPenaltyRequestSize))),b((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=v();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(g()).subscribe((t=>{e=t.loaded,s=v()})));break;case 1:case 0:a.add(r(t,'loadstart').subscribe((()=>{e=0,s=v()})))}a.add(r(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,a=v(),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=v();let a=0,r=v();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,v()-s,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,a+=h.byteLength,a>=this.tuningConfig.streamMinSampleSize&&v()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,v()-r,this.concurrentDownloads.size),a=0,r=v()),await(e?.read().then(o,n)))};this.concurrentDownloads.add(t),e?.read().then(o,n)}addRawSpeed(t,e,i=1){if(Bi.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(Ri){case Ai.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Ai.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Ai.RUNTIME:return Pi.get(t);default:n(Ri)}})(t);if(s(e))return parseInt(e,10)??void 0}}const Ni={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}};const Mi=({playbackState:t,seekState:e,playbackAbort$:r,looped$:n,position$:d})=>new y((u=>{let c;const l=t.transitionEnded$.pipe(b((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=t.stateChangeEnded$.pipe(b((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),m=e.stateChangeEnded$.pipe(b((({to:e})=>e.state===I.Requested&&(t.getTransition()?.from??t.getState())===P.PLAYING))),f=e.stateChangeEnded$.pipe(b((({from:e,to:i})=>e.state===I.Applying&&i.state===I.None&&(t.getTransition()?.from??t.getState())===P.PLAYING))),g=o(l,f).pipe(h((()=>d.getValue())),b(s)),S=o(o(p,m,r),n).pipe(h((()=>d.getValue())),b(s));return(new i).add(g.subscribe((t=>{c=t}))).add(S.subscribe((t=>{if(a(c)||c===t)return;const e={from:c,to:t};c=void 0,u.next(e)})))})),Oi={[D.SCREEN]:{vod:[...pi?[R.HLS,R.HLS_ONDEMAND]:[],R.DASH_WEBM,R.DASH_SEP,R.DASH,R.DASH_ONDEMAND,...pi?[]:[R.HLS,R.HLS_ONDEMAND],R.MPEG],live:pi?[R.WEB_RTC_LIVE,R.HLS_LIVE,R.DASH_LIVE]:[R.WEB_RTC_LIVE,R.DASH_LIVE,R.HLS_LIVE]},[D.CHROMECAST]:{vod:[R.DASH_WEBM,R.DASH_SEP,R.DASH_ONDEMAND,R.HLS,R.HLS_ONDEMAND,R.MPEG],live:[R.HLS_LIVE]}};class Ui{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new k;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new Y(P.STOPPED),seekState:new Y({state:I.None}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({})};info={playbackState$:new t(P.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentPlaybackRate$:new t(1),currentBuffer$:new t({start:0,end:0}),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(_.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)};events={inited$:new e,started$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,canplay$:new e,log$:new e};experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:kt};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Ni)){const s=Ni[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:a??s}return e})(t),this.chromecastInitializer=new L({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bi(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 wi({screenFormatsPriority:[...Oi[D.SCREEN].live,...Oi[D.SCREEN].vod],chromecastFormatsPriority:[...Oi[D.CHROMECAST].live,...Oi[D.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:I.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t,!1),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){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}setPlaybackRate(t){l(this.providerContainer);const e=this.providerContainer?.providerOutput.element$.getValue();return e&&(this.desiredState.playbackRate.setState(t),e.playbackRate=t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){return(void 0===t||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t)))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){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===I.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.playbackRate.stateChangeEnded$.pipe(h((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).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$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((()=>!this.isPlaybackStarted)),b((t=>t.to===P.PLAYING))).subscribe((()=>{this.isPlaybackStarted=!0,this.initedAt=v(),this.events.inited$.next(),this.events.started$.next()}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case P.PAUSED:this.events.willPause$.next();break;case P.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===I.Requested?this.desiredState.seekState.setState({...t,state:I.Applying}):this.events.managedError$.next({id:`WillSeekIn${t.state}`,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===I.Applying&&(this.desiredState.seekState.setState({state:I.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)=>G(t)?1:G(e)?-1:V(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(t?.quality),this.info.videoBitrate$.next(t?.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(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===I.None?void 0:(t.position??NaN)/1e3)),b(s)),e.pipe(b((()=>t.getState().state===I.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(S(!0)),e.providerOutput.seekedEvent$.pipe(S(!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(g(),h((()=>v()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(g(),h((()=>v()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(g(),h((()=>v()-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(b((({to:t})=>t===P.PLAYING)),g()).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(b((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((e=>{switch(l(this.providerContainer),p.unsubscribe(),e){case!0:{const e=new t(void 0);p.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),p.add(Mi({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:m,looped$:this.events.looped$,position$:e}).pipe(h((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:p.add(Mi({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(b((t=>t.length>0)),g()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=_t(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(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=>{wt=t})),this.providerContainer.current$.subscribe((({type:t})=>At('provider',t))),t.duration$.subscribe((t=>At('duration',t))),t.availableVideoTracks$.pipe(b((t=>!!t.length)),g()).subscribe((t=>At('tracks',t))),this.events.fatalError$.subscribe(new Pt('fatalError')),this.events.managedError$.subscribe(new Pt('managedError')),t.position$.subscribe(new Pt('position')),t.currentVideoTrack$.pipe(h((t=>t?.quality))).subscribe(new Pt('quality')),this.info.currentBuffer$.subscribe(new Pt('buffer')),t.isBuffering$.subscribe(new Pt('isBuffering'))].forEach((t=>this.subscription.add(t))),At('codecs',Object.keys(ui).filter((t=>ui[t])))}}const Vi='@vkontakte/videoplayer-core@2.0.75';export{_ as ChromecastState,C as HttpConnectionType,P as PlaybackState,Ui as Player,Vi as SDK_VERSION,R as VideoFormat,N as VideoQuality};
6
+ import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,ErrorCategory as a,isNullable as r,fromEvent as n,assertNever as o,merge as d,tap as h,map as u,observableFrom as c,filterChanged as l,assertNonNullable as p,debounce as m,timeout as f,combine as g,once as S,mapTo as b,filter as v,now as y,Observable as T,abortable as E,getExponentialDelay as w,interval as $,Logger as k}from'@vkontakte/videoplayer-shared/esnext.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/esnext.esm.js';import A from'lodash/debounce.js';var P,R,D,_,I,C;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS',t.HLS_LIVE='HLS_LIVE',t.WEB_RTC_LIVE='WEB_RTC_LIVE'}(R||(R={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(D||(D={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(_||(_={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(I||(I={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(C||(C={}));class L{connection$=new t(void 0);castState$=new t(_.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(_.NOT_AVAILABLE);subscription=new i;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const e='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${e}`}),t.isDisabled||!e)return;const i=s(window.chrome?.cast),r=Boolean(window.__onGCastApiAvailable);var n;i?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{delete window.__onGCastApiAvailable,t&&this.initializeCastApi()},r||(n='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',n),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',category:a.NETWORK,message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();r(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();r(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(n(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return o(t.sessionState)}}))).add(d(n(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(h((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),c([i.getCastState()])).pipe(l(),u(x),h((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{const n=a===_.CONNECTED,o=s(this.connection$.getValue());if(n&&!o){const s=i.getCurrentSession();p(s);const a=s.getCastDevice(),n=s.getMediaSession()?.media.contentId;(r(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===_.CONNECTED?s(this.connection$.getValue())?_.CONNECTED:_.AVAILABLE:a)})))}initializeCastApi(){let t,e,i;try{t=cast.framework.CastContext.getInstance(),e=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{t.setOptions({receiverApplicationId:this.params.receiverApplicationId??e,autoJoinPolicy:i}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',category:a.EXTERNAL_API,message:'[initializeCastApi] failed',thrown:t})}}}const x=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _.AVAILABLE;case cast.framework.CastState.CONNECTING:return _.CONNECTING;case cast.framework.CastState.CONNECTED:return _.CONNECTED;default:return o(t)}};var N;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(N||(N={}));var B,O=(t,e=0,i=N.OFFSET_P)=>{switch(i){case N.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case N.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:o(i)}return t},M=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(B||(B={}));const U={[B.Q_144P]:{width:256,height:144},[B.Q_240P]:{width:428,height:240},[B.Q_360P]:{width:640,height:360},[B.Q_480P]:{width:856,height:480},[B.Q_720P]:{width:1280,height:720},[B.Q_1080P]:{width:1920,height:1080},[B.Q_1440P]:{width:2560,height:1440},[B.Q_2160P]:{width:3840,height:2160},[B.Q_4320P]:{width:7680,height:4320}},V=(t,e)=>U[t].height>U[e].height,F=(t,e)=>U[t].height<U[e].height,q=Object.keys(U).sort(((t,e)=>F(t,e)?-1:1)),H=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return q.find((t=>{const e=U[t];return e.width>=s&&e.height>=i}))},G=t=>t===B.INVARIANT;class Y{state;transition;transitionStarted$=new e;transitionEnded$=new e;transitionUpdated$=new e;forceChanged$=new e;stateChangeStarted$=d(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=d(this.transitionEnded$,this.forceChanged$);constructor(t){this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var z;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(z||(z={}));class Q{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new Y(z.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case R.MPEG:case R.DASH:case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:case R.HLS:case R.HLS_ONDEMAND:return!1;case R.HLS_LIVE:case R.DASH_LIVE:case R.DASH_LIVE_WEBM:case R.WEB_RTC_LIVE:return!0;default:return o(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(d(this.videoState.stateChangeStarted$.pipe(u((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(u((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const s=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new e;t.add(i.pipe(m(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;t.add(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===C.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),t.add(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),a=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==a&&this.params.output.isBuffering$.next(a),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),M(this.params.desiredState.playbackState,P.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:o(i)}})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));s(d(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(z.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(z.PLAYING),M(this.params.desiredState.playbackState,P.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==z.PAUSED&&t!==z.PLAYING||(this.videoState.setState(z.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==z.PLAYING&&t!==z.PAUSED||(this.videoState.setState(z.PLAYING),M(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY)}handleRemoteStop(){this.videoState.getState()!==z.STOPPED&&this.videoState.setState(z.STOPPED)}handleRemoteVolumeChange(t){const e=this.params.output.volume$.getValue(),i={volume:t.volume??e.volume,muted:t.muted??e.muted};i.volume===e.volume&&i.muted==i.muted||this.params.output.volume$.next(i)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){const e=this.params.source;let i,r,n;switch(t){case R.MPEG:{const s=e[t];p(s);const a=Object.keys(s).sort(((t,e)=>t===e?0:t===B.INVARIANT?1:e===B.INVARIANT?-1:F(t,e)?1:-1))[0];p(a);const o=s[a];p(o),i=o,r='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case R.HLS:case R.HLS_ONDEMAND:{const s=e[t];p(s),i=s.url,r='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:{const s=e[t];p(s),i=s.url,r='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case R.HLS_LIVE:{const s=e[t];p(s),i=O(s.url),r='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case R.DASH:case R.DASH_LIVE:case R.WEB_RTC_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',category:a.VIDEO_PIPELINE,message:t,thrown:e}),e}case R.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return o(t)}const d=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);d.contentUrl=i,d.streamType=n,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:h,subtitle:u}=this.params.meta;return s(h)&&(d.metadata.title=h),s(u)&&(d.metadata.subtitle=u),d}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===C.Applying||i.state===C.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(f(7e3).subscribe((()=>e('timeout(7000)'))))}));Promise.race([e,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',category:a.VIDEO_PIPELINE,message:e,thrown:t})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)if(s?.to===P.PAUSED||a.state!==C.Requested||t===z.STOPPED)switch(i){case P.PLAYING:switch(t){case z.PLAYING:break;case z.PAUSED:case z.READY:this.videoState.startTransitionTo(z.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();break;default:o(t)}break;case P.PAUSED:switch(t){case z.PLAYING:this.videoState.startTransitionTo(z.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case z.PAUSED:break;case z.READY:this.videoState.startTransitionTo(z.PAUSED),this.videoState.setState(z.PAUSED);break;case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();break;default:o(t)}break;default:o(i)}else this.seek(a.position)}else t!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.stop())}}class W{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}removeEventListener(t,e){if(!(t in this.listeners))return;const i=this.listeners[t];for(let t=0,s=i.length;t<s;t++)if(i[t].callback===e)return void i.splice(t,1)}dispatchEvent(t){if(!(t.type in this.listeners))return;const e=this.listeners[t.type].slice();for(let i=0,s=e.length;i<s;i++){const s=e[i];try{s.callback.call(this,t)}catch(t){Promise.resolve().then((()=>{throw t}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}class j extends W{constructor(){super(),this.listeners||W.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class J{constructor(){Object.defineProperty(this,'signal',{value:new j,writable:!0,configurable:!0})}abort(){let t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event'),t.initEvent('abort',!1,!1)):(t=document.createEventObject(),t.type='abort'):t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}toString(){return'[object AbortController]'}}function X(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(J.prototype[Symbol.toStringTag]='AbortController',j.prototype[Symbol.toStringTag]='AbortSignal');const K=X({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Z=K?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=t;if(!X({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const a=new i(t,e);return s&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),a},r.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=r&&r.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const a=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,n(t,e)])}return n(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,tt=K?Z.fetch:window.fetch;K?Z.Request:window.Request;const et=K?J:window.AbortController,it=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class st{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){const{url:e}=t.request,i=this.dashJsRequestQueue.get(e)??[];i.push(t),this.dashJsRequestQueue.set(e,i)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=it(s.request);if(a>=i.from&&r<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){if(t){const{request:e}=t,i=(this.dashJsRequestQueue.get(e.url)??[]).includes(t),s=this.activeRequests.get(e.url);i&&s&&s.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(it),s=i[0][0];let r=i[0][1];for(let t=1;t<i.length&&r<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===s?Math.max(r,s+this.params.minInitSize):Math.max(r,s+this.params.minDataSize);const n=new URL(t,location.href);n.searchParams.append('bytes',`${s}-${r}`);const o=n.toString(),d=new et,h=d.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:d};h.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const c=t=>{throw this.params.onError?.({id:'BigRequestParsing',category:a.PARSER,message:'Error parsing response data',thrown:t}),t};return tt(o,{signal:h}).then((t=>{if(u.response=t,!t.ok||!t.body)return void this.onBigRequestError(u);const[e,i]=t.body.tee();this.params.onDownloadStream?.(i);const a=e.getReader(),n=parseInt(t.headers.get('Content-Length')??'',10)||r-s+1;u.data=new ArrayBuffer(n);const o=new Uint8Array(u.data),d=async({done:t,value:e})=>{t?this.onBigRequestProgress(u):e&&(o.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),await(a?.read().then(d,st.suppressStreamErrors).catch(c)))};a?.read().then(d,st.suppressStreamErrors).catch(c)}),st.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a,response:r}){if(!this.activeRequests.has(t)||!a)return;const n=this.dashJsRequestQueue.get(t)??[];for(const o of n){const{request:n}=o,[d,h]=it(n),u=d>=e&&h<=e+s,c=e>=d&&e+s<h,l=a.slice(d-e,Math.min(h-e+1,s));if((u||c)&&(n.requestStartDate=n.requestStartDate??new Date,n.firstByteDate=n.firstByteDate??new Date,n.bytesLoaded=l.byteLength,n.bytesTotal=i-e),u){n.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(this.dashJsRequestQueue.get(t)??[]).filter((t=>t!==o))),o.success?.(l,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';this.dashMetrics?.addHttpRequest(n,t,r?.status??200,e,[])}else c&&o.progress?.({loaded:s,total:i-e,lengthComputable:!0,stream:!0})}}onBigRequestError({url:t,from:e,to:i},s){if(this.params.onError?.({id:'BigRequest',category:a.NETWORK,message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const r=this.dashJsRequestQueue.get(t)??[];for(const t of r){const[a,r]=it(t.request);(a>=e&&a<i||r>e&&r<=i)&&t?.error?.(t.request,String(s))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){if(!this.activeRequests.has(t))return;const s=this.dashJsRequestQueue.get(t)??[];for(const t of s){const[s,a]=it(t.request);(s>=e&&s<i||a>e&&a<=i)&&t?.abort?.(t.request)}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class at{baseLoader;config;bigRequest;constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(at.shouldDelegateToBase(e))return this.baseLoader.load(t);this.bigRequest.queueDashJSRequest(t),this.bigRequest.executeNextRequests()}abort(t){if(!t)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:e}=t;at.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const rt=(t,e)=>{const i=new st(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new at(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var nt=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&e?.()})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&e?.()}}}),!0)},ot=i=>{const a=new t(1/0),r=new e,n=new t(void 0),o=new t(void 0);let d=NaN,h=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{const e=Object.fromEntries(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in e||'x-playback-duration-millis'in e){const e=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),i=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*e??NaN;s(i)&&!isNaN(i)&&a.next(i)}const i=e['x-delivery-type']??I.HTTP1,r={1:!0,0:!1}[e['x-reused']]??void 0;n.next(i),o.next(r)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!h&&(h=!0,r.next(Date.now()-d)),i(...t)},d=Date.now(),h=!1}return e(t)}}}),!0),{playbackDuration$:a,ping$:r,connectionReused$:o,connectionType$:n}},dt=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},ht=t=>{t.extend('HTTPLoader',(function(){const{parent:t}=this,e=t.load;return{load:t=>{if(t.request&&t.request.range){const[e,i]=t.request.range.split('-').map((t=>parseInt(t,10))),s=new URL(t.request.url,location.href);s.searchParams.append('bytes',`${e}-${i}`),t.request.url=s.toString(),t.request.range=void 0}e(t)}}}),!0)};const ut=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),h=e(),u=r(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(h,d)||(s(d),u&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),u&&t.setState(e.to)}),o)),c},ct=(t,e,i)=>ut(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),lt=(t,e,i,a)=>ut(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||t?.muted===e?.muted&&t?.volume===e?.volume,changed$:i,onError:a}),pt=(t,e,i,a)=>ut(e,(()=>t.playbackRate),(e=>{s(e)&&(t.playbackRate=e)}),{changed$:i,onError:a}),mt=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class ft{available$=new e;current$=new t(void 0);error$=new e;video;cueSettings;subscription=new i;externalTracks=new Map;connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',category:a.WTF,message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ut(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(u((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(ut(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:r})),this.subscription.add(ut(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){p(this.video);const{textTracks:t}=this.video;this.subscription.add(n(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(d(n(t,'addtrack'),n(t,'removetrack'),c(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),l(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(d(n(t,'change'),c(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),l()).subscribe(this.current$));const e=t=>this.applyCueSettings(t.target?.activeCues??null);this.subscription.add(n(t,'addtrack').subscribe((t=>{t.track?.addEventListener('cuechange',e);const i=t=>{const e=t.target?.cues??null;e&&e.length&&(this.applyCueSettings(t.target?.cues??null),t.target?.removeEventListener('cuechange',i))};t.track?.addEventListener('cuechange',i)}))),this.subscription.add(n(t,'removetrack').subscribe((t=>{t.track?.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){p(this.video);const e=[...this.video.textTracks];return t?e:e.filter(ft.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){p(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&mt(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){p(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){p(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var gt=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),e.setAttribute('poster','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='),t.appendChild(e),e};class St{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}var bt=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};class vt{_buffer=[];_source;constructor(t){this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:a})=>{const r=s>=t&&s<e,n=a>=t&&a<e;r&&n||(r?i(e,a):n?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var yt=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(s=n,a=o,!i)return{from:s,to:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{from:s,to:a}};const Tt=t=>{const i=e=>n(t,e).pipe(b(void 0)),r=d(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>n(t,e)))).pipe(u((e=>'ended'===e.type?t.readyState<2:t.readyState<3)),l()),o=d(n(t,'progress'),n(t,'timeupdate')).pipe(u((()=>yt(t.buffered,t.currentTime)))),h=bt()?g({play:i('play').pipe(S()),playing:i('playing')}).pipe(b(void 0)):i('playing'),c=n(t,'volumechange').pipe(u((()=>({muted:t.muted,volume:t.volume})))),p=n(t,'ratechange').pipe(u((()=>t.playbackRate))),m=n(t,'error').pipe(v((()=>Boolean(t.error||t.played.length))),u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',category:a.VIDEO_PIPELINE,message:e?e.message:'Error event from HTML video element',thrown:t.error??void 0}}))),f=n(t,'timeupdate').pipe(u((()=>t.currentTime))),y=new e;let T;return f.subscribe((e=>{t.loop&&s(T)&&s(e)&&T>=t.duration-.3&&e<=.3&&y.next(T),T=e})),{playing$:h,pause$:i('pause').pipe(v((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:y,error$:m,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:f,durationChange$:n(t,'durationchange').pipe(u((()=>t.duration))),isBuffering$:r,currentBuffer$:o,volumeState$:c,playbackRateState$:p}},Et=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};let wt=!1,$t={};const kt=t=>{t($t)},At=(t,e)=>{wt&&($t.meta=$t.meta??{},$t.meta[t]=e)};class Pt{name;constructor(t){this.name=t}next(t){if(!wt)return;$t.series=$t.series??{};const e=$t.series[this.name]??[];e.push([Date.now(),t]),$t.series[this.name]=e}}const Rt=new Pt('best_bitrate');class Dt{last;history={};recordSelection(t){this.history[t.id]=y()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const _t=(t,{container:e,throughput:i,tuning:a,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:h,current:u,history:c})=>{const l=a.usePixelRatio?window.devicePixelRatio??1:1,p=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*a.containerSizeFactor,height:e.height*l*a.containerSizeFactor},m=p&&H(p),f=a.considerPlaybackRate&&s(h)?h:1,g=t.filter((t=>!G(t.quality))).sort(((t,e)=>V(t.quality,e.quality)?-1:1)),S=g.at(-1)?.quality,b=g.at(0)?.quality,v=r(n)||s(n.min)&&s(n.max)&&F(n.max,n.min)||s(n.min)&&b&&V(n.min,b)||s(n.max)&&S&&F(n.max,S),T=f*(E=d??.5,w=a.bitrateFactorAtEmptyBuffer,$=a.bitrateFactorAtFullBuffer,(w-$)*Math.pow(2,-10*E)+$);var E,w,$;const k=g.filter((t=>{const e=!m||F(t.quality,m),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*T,c=a.lazyQualitySwitch&&s(a.minBufferToSwitchUp)&&u&&!G(u.quality)&&(d??0)<a.minBufferToSwitchUp&&V(t.quality,u.quality),l=v||(r(n.max)||(p=t.quality,f=n.max,U[p].height<=U[f].height))&&(r(n.min)||((t,e)=>U[t].height>=U[e].height)(t.quality,n.min));var p,f;return e&&h&&!c&&l}))[0];k&&k.bitrate&&Rt.next(k.bitrate);const A=k??g[Math.ceil((g.length-1)/2)]??t[0],P=A&&c&&c.history[A.id]&&y()-c.history[A.id]<=a.trackCooldown&&(!c.last||A.id!==c.last.id);if(A?.id&&c&&!P&&c.recordSelection(A),P&&c?.last){const t=c.last;return c?.recordSwitch(t),t}return c?.recordSwitch(A),A};var It=t=>new URL(t).hostname;const Ct=(t,e=300)=>new T((i=>{const{width:a,height:r}=t.getBoundingClientRect();if(i.next({width:a,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let a,r;e.contentBoxSize&&e.contentBoxSize[0]?(r=e.contentBoxSize[0].blockSize,a=e.contentBoxSize[0].inlineSize):e.contentRect&&(a=e.contentRect.width,r=e.contentRect.height),s(a)&&s(r)&&i.next({width:a,height:r})}),e));return n.observe(t),()=>n.disconnect()})),Lt={};var xt;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(xt||(xt={}));const Nt=(t,e)=>new T((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Bt{subscription=new i;videoState=new Y(xt.DOWNLOADING_LIB);video;player;params;textTracksManager=new ft;videoTracks=[];frameRatesByFrameHeight={};isLive$=new t(void 0);maxSeekBackTime$=new t(1/0);availableFrom$=new t(void 0);elementSize$=new t(void 0);liveOffset=new St;destroyBigRequest;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',category:a.NETWORK,message:`Dash.js failed to load: ${e?.toString?.()}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Lt.MediaPlayer=e.MediaPlayer,Lt.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){p(Lt.MediaPlayer,'dashjs not loaded'),p(Lt.Debug,'dashjs not loaded'),this.player=Lt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter((t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Et(t.frameRate+''):void 0),!0)));(this.params.format===R.DASH_WEBM||this.params.format===R.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=rt(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&ht(this.player),nt(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:dt})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(xt.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',category:a.WTF,message:'DashIFProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(Ct(this.video),this.elementSize$),n(Nt(this.player,'error').pipe(u((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),n(Nt(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const o=Nt(this.player,'qualityChangeRendered').pipe(v((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));o.pipe(v(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(v((({to:t})=>t===xt.STREAM_INITIALIZED)),S()).subscribe((()=>{this.subscription.add(ut(e.videoTrack,(()=>{const t=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track?.id}),(t=>{if(r(t))return;const e=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;e&&this.player.setQualityFor('video',e.qualityIndex)}),{changed$:o.pipe(u((t=>t?.id))),onError:i}))}),i)),this.subscription.add(ut(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),n(Nt(this.player,'bufferStateChanged').pipe(v((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),n(Nt(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{const s=this.player.getDashMetrics(),a=s.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),r=s.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type')??I.HTTP1,n={1:!0,0:!1}[a]??void 0;this.params.output.httpConnectionType$.next(r),this.params.output.httpConnectionReused$.next(n),t.hostname$.next(It(i))})),n(Nt(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=H(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(xt.STREAM_INITIALIZED),this.videoState.startTransitionTo(xt.READY)})),n(Nt(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),n(d(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=_t(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));s?.bitrateInfo&&this.player.setQualityFor('video',s?.bitrateInfo.qualityIndex,!1)})),n(g({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(v(s))}).pipe(v((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const h=Nt(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>t??0)));n(g({availableFrom:this.availableFrom$.pipe(v(s)),currentTime:h}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),n(h.pipe(v((()=>!1===this.isLive$.getValue()))),t.position$),n(Nt(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),n(Nt(this.player,'playbackEnded'),t.endedEvent$),n(Nt(this.player,'playbackProgress').pipe(u((()=>yt(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),n(Nt(this.player,'playbackPlaying'),(()=>{this.videoState.setState(xt.PLAYING),M(e.playbackState,P.PLAYING)})),n(Nt(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(xt.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),n(Nt(this.player,'playbackPaused'),(()=>{this.videoState.setState(xt.PAUSED),M(e.playbackState,P.PAUSED)})),n(Nt(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===xt.READY&&this.videoState.setState(xt.READY)})),n(this.isLive$,t.isLive$),n(Ct(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));n(d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)),this.syncPlayback);const{playbackDuration$:l,ping$:p,connectionType$:f,connectionReused$:y}=ot(this.player);n(f,this.params.output.httpConnectionType$),n(y,this.params.output.httpConnectionReused$),n(l,this.maxSeekBackTime$),n(p.pipe(S()),t.firstBytesEvent$),n(Nt(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&n(g({isLive:this.isLive$,isShort:t.duration$.pipe(u((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),n(h.pipe(v((t=>t>this.params.tuning.insufficientBufferRuleMargin)),S()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Nt(this.player,'manifestLoaded').pipe(S()).subscribe((()=>{this.subscription.add(Nt(this.player,'playbackPlaying').pipe(S(),b(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(ct(this.video,e.isLooped,i));const{volumeState$:T,looped$:E,playbackRateState$:w}=Tt(this.video);this.subscription.add(lt(this.video,e.volume,T,i)),this.subscription.add(T.subscribe(t.volume$,i)),this.subscription.add(E.subscribe(t.loopedEvent$)),this.subscription.add(pt(this.video,e.playbackRate,w,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(xt.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(xt.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=O(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,N.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(xt.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(xt.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==xt.DOWNLOADING_LIB&&t!==xt.STREAM_INITIALIZED)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&t!==xt.STOPPED&&e!==P.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case xt.STOPPED:break;case xt.PLAYING:case xt.PAUSED:case xt.READY:this.stop();break;default:o(t)}break;case P.PLAYING:switch(t){case xt.PLAYING:break;case xt.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case xt.READY:this.play();break;case xt.STOPPED:this.prepare();break;default:o(t)}break;case P.PAUSED:switch(t){case xt.PLAYING:this.pause(),this.liveOffset.pause();break;case xt.PAUSED:break;case xt.READY:this.videoState.setState(xt.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED);break;case xt.STOPPED:this.prepare();break;default:o(t)}break;default:o(e)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Ot=t=>{switch(t){case'mobile':return B.Q_144P;case'lowest':return B.Q_240P;case'low':return B.Q_360P;case'sd':case'medium':return B.Q_480P;case'hd':case'high':return B.Q_720P;case'fullhd':case'full':return B.Q_1080P;case'quadhd':case'quad':return B.Q_1440P;case'ultrahd':case'ultra':return B.Q_2160P}},Mt=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function Ut(){return y()}function Vt(t){return Ut()-t}function Ft(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function qt(t,e,i,a){const r=window.XMLHttpRequest;let n,o,d,h,u,c=!1,l=0,m=!1,f='arraybuffer',g=7e3,S=2e3,b=()=>{if(c)return;p(h);const t=Vt(h);let e;if(t<S)return e=S-t,void setTimeout(b,e);S*=2,S>g&&(S=g),o&&o.abort(),o=new r,y()};const v=()=>{if(!c){if(--l>=0)return b(),void(a&&a());c=!0,u&&u(),i&&i()}},y=()=>{h=Ut(),o=new r,o.open('get',t);let i,s=0,a=0;const l=()=>(p(h),Math.max(h,Math.max(i||0,a||0)));if(n&&o.addEventListener('progress',(t=>{const e=Ut();n.updateChunk&&t.loaded>s&&(n.updateChunk(l(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(c)return;p(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(l(),t)}u&&u(),o&&e(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),m){const t=()=>{p(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(a=Ut(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=f,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(m=t,T),withJSONResponse:()=>(f='json',T),withRetryCount:t=>(l=t,T),withRetryInterval:(t,e)=>(s(t)&&(S=t),s(e)&&(g=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(u=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,u&&u()}};return T}class Ht{intervals=[];currentRate=0;logger;constructor(t){this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const n=t.bytes*a/r;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:'warn'}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}}class Gt{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(t,e,i,s,a){this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=Ut(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=qt(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Ut()-i,delete this.activeRequests[e],this._sendPending(),t._cb?t._cb(s,t._downloadTime):(this.limitCompleteCount(),this.completeRequests[e]=t)}),(()=>s('error')),(()=>{t._retry=1,t._retryCB&&t._retryCB()})),t._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{t._finallyCB&&t._finallyCB()})),this.activeRequests[e]=t,t._request.send(),this.lastPrefetchStart=Ut()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const t=this._getParallelRequestCount(),e=Ut();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class Yt{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(t){this.params=t,this.chunkRateEstimator=new Ht(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Ft(t),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(t){this.autoQuality=t}setMaxAutoQuality(t){this.maxAutoQuality=t}switchByName(t){let e;for(let i=0;i<this.manifest.length;++i)if(e=this.manifest[i],e.name===t)return void this._switchToQuality(e)}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(t){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(t):this._notifyBuffering(!0)):this.catchUp()}startPlay(t,e){this.autoQuality=e,this._initPlayerWith(t)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(t){this.manifestUrl=t,this.urlResolver=Ft(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(()=>{Boolean(t.error)&&!this.destroyed&&(e(`Video element error: ${t.error?.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gt(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,d=null,h=null,u=null,c=!1;const l=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{h&&h.abort(),h=qt(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{h=null})).send()},f=(t,e,i)=>{p(this.filesFetcher),d?.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},g=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},S=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void g(1);const i=Ut()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const a=this.bufferStates[e];t=Math.min(t,a.buf),a.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,g(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else g(1)},v=t=>{let i;const r=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,h=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=e;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=i.dur.length-1;for(;r>=0&&(a-=i.dur[r],!(a<=0));--r);t=Math.min(r,i.dur.length-1-s),t=Math.max(t,0)}return h(t,!0)},m=(t,e,i)=>{u&&u.abort(),u=qt(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!l())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&S(d);let u=0;for(let t=0;t<i.dur.length;++t)u+=i.dur[t];u>0&&(p(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=r();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return h(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=r(),a=t?t.chunkIdx+1:0,n=a-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return h(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),h&&h.abort(),u&&u.abort(),p(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,h,c,g,S,T,E=v(t.jidxUrl),w=0;const $=()=>{g&&(clearTimeout(g),g=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Ut(),s=Math.min(1e4,e-i);w=i;const a=()=>{u||l()&&E.seek((()=>{l()&&(w=Ut(),k(),$())}))};s>0?g=window.setTimeout((()=>{this.paused?$():a()}),s):a()},k=()=>{let e;for(;e=E.nextChunk(c);)c=e,_(e);const i=E.nextChunk(h);if(i){if(h&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));D(i)}else $()},A=(t,e)=>{if(!l()||!this.sourceBuffer)return;let a,r,n;const o=i=>{window.setTimeout((()=>{l()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Ut(),h=i.currentTime;!this.paused&&i.buffered.length>1&&S===h&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),S!==h&&(S=h,T=d);const u=this._getBufferSizeSec();if(u>30)s(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(a=this.sourceBuffer.buffered.start(0),r=h,r-a>4&&this.sourceBuffer.remove(a,r-3)),o(1e3)}}},P=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),A(d,(function(){d=null,k()})))},R=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{l()&&f(R(t),((e,i)=>{if(l()){if(i/=1e3,d=e,h=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}P()}}),(()=>this._handleNetworkError()))},_=t=>{l()&&(p(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(R(t),!1)))},I=e=>{l()&&(t.cachedHeader=e,A(e,(()=>{a=!0,P()})))};n=!0,E.seek((t=>{l()&&(w=Ut(),t?(c=t,!r(e)||t.startTS>e?D(t):(h=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),s(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,p(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Ut();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(n&&t>a&&Vt(r)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=Ut();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=qt(this.urlResolver.resolve(t,!0),e,i,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;Mt(e).then((e=>{e||t?.()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return t?.length?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var zt;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(zt||(zt={}));const Qt=[zt.PAUSED,zt.PLAYING,zt.READY],Wt=[zt.PAUSED,zt.PLAYING,zt.READY];class jt{subscription=new i;video;videoState=new Y(zt.STOPPED);dash;representations$=new t([]);textTracksManager=new ft;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new St;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const e=e=>{t.output.error$.next({id:'DashLiveProvider',category:a.WTF,message:'DashLiveProvider internal logic error',thrown:e})};d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Tt(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===zt.READY&&this.videoState.setState(zt.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(zt.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(zt.PLAYING)}),e)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(l(),u((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(g({zeroTime:this.zeroTime$.pipe(v(s)),position:i.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(ct(this.video,this.params.desiredState.isLooped,e)).add(lt(this.video,this.params.desiredState.volume,i.volumeState$,e)).add(i.volumeState$.subscribe(this.params.output.volume$,e)).add(pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,e)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&U[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case zt.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case zt.MANIFEST_READY:case zt.READY:break;case zt.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case zt.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return o(t.to)}}),e)).add(d(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekState.stateChangeEnded$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)).subscribe(this.syncPlayback,e))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Yt({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){const t=this.representations$.getValue(),e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s(e)?e:_t(t.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.id,r=t.find((({track:t})=>t.id===a))?.representation;p(r,'Representations missing'),this.dash.startPlay(r,i),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(i)}setVideoTrack(t){const e=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;p(e,`No such representation ${t}`),this.dash.switchByName(e.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(O(this.params.source.url,i))}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,category:a.WTF,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,i=[];for(const t of e){const e=t.name??t.index.toString(10),s=Ot(t.name)??H(t.video),a=t.bitrate/1e3,r={...t.video};if(!s)continue;const n={id:e,quality:s,bitrate:a,size:r};i.push({track:n,representation:t})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map((({track:t})=>t))),this.videoState.getTransition()?.to===zt.MANIFEST_READY&&this.videoState.setState(zt.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=this.representations$.getValue().find((({representation:t})=>t===e))?.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e){if(Wt.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;s(t)&&this.setVideoTrack(t);const e=this.params.desiredState.autoVideoTrackSwitching.getTransition();e&&this.setAutoQuality(e.to)}if(a?.to!==P.PAUSED&&r.state===C.Requested&&Qt.includes(t))this.seek(r.position-this.liveOffset.getTotalPausedTime());else switch(t){case zt.STOPPED:return this.videoState.startTransitionTo(zt.MANIFEST_READY),void this.dash.attachSource(O(this.params.source.url));case zt.MANIFEST_READY:this.videoState.startTransitionTo(zt.READY),this.prepare();break;case zt.READY:return void(i===P.PAUSED?this.videoState.setState(zt.PAUSED):i===P.PLAYING&&(this.videoState.startTransitionTo(zt.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(zt.PAUSED)}))));case zt.PLAYING:return void(i===P.PAUSED&&(this.videoState.startTransitionTo(zt.PAUSED),this.liveOffset.pause(),this.dash.pause()));case zt.PAUSED:return void(i===P.PLAYING&&(this.videoState.startTransitionTo(zt.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(zt.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return o(t)}}}else t!==zt.STOPPED&&(this.videoState.startTransitionTo(zt.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(zt.STOPPED))}}var Jt=t=>{const e=t.get('X-Delivery-Type'),i=t.get('X-Reused');return{type:null===e?I.HTTP1:e??void 0,reused:null===i?void 0:{1:!0,0:!1}[i]??void 0}},Xt=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)};class Kt{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(t,e=[],i,s,a,r){this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(p(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Zt{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(t){this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),e?.()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,c=0;const l=t=>{s(Zt._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=dt(p)),this._lastXhr=new Kt(p,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),a?.()}),(t=>{if(t.length-o>n&&l(t),0===u)return void(u=Date.now());c=t.length-h;const e=Date.now()-u;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,h=t.length,u=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),t?.()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Zt._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class te{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(t){this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=t.onDashCallback??(()=>{}),this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===i?.[1]?-1:1;e(i?.[2],s),e(i?.[3],s),e(i?.[4],s),e(i?.[5],s);return 3600*e(i?.[6],s)+60*e(i?.[7],s)+e(i?.[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=dt(i)),new Kt(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{const s=t.getElementsByTagName('SegmentBase')[0],o=s&&a(s,'indexRange').split('-'),d=s&&s.getElementsByTagName('Initialization')[0],h=d&&a(d,'range').split('-');if(!h||!o){const e=t.parentElement;if('text'===e?.getAttribute('contentType')){const s=t.getAttribute('id')??void 0,a=(i?i+'/':'')+t.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=e.getAttribute('lang')??void 0;a&&n.push({id:s,url:a,language:r})}return}const u=Number(t.attributes.getNamedItem('bandwidth')?.value),c=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=t.attributes.getNamedItem('frameRate')?.value??void 0;l=p?Et(p):void 0,r.push({width:Number(t.attributes.getNamedItem('width')?.value),height:Number(t.attributes.getNamedItem('height')?.value),bandwidth:u,baseURL:c,failoverHosts:e,indexFrom:Number(o[0]),indexTo:Number(o[1]),initFrom:Number(h[0]),initTo:Number(h[1]),codecs:t.attributes.getNamedItem('codecs')?.value??void 0,mimeType:t.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*u/8,bufferLength:.1,name:t.attributes.getNamedItem('okQuality')?.value??void 0,id:t.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let n=a.getUint32(s,!1),o=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&a.getUint32(s,!1)),i=n+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/r,toTime:i/r,fromOffset:o,toOffset:e-1}),o=e,n=i}const h=t.refs[t.refs.length-1];h.toTime-h.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let r;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.to-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.to&&(a=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new Zt({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const a=this._findRef(e);if(a){if(i){this._isLastRef(a)&&e>=a.toTime&&(e=a.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:a.fromTime}this._appendVector[String(a.fromTime)]=t,this._stream.load(t,a.fromOffset,a.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const a=.1;if(s.toTime<i.to+a){const e=this._findRef(s.toTime);e&&e.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!r(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){const e=this._currentRepresentation?.refs;if(!e)return;if(Array.isArray(e)&&0===e.length)return void this._params.onError('emptyrefs','Empty refs');let i;for(let s=0;s<e.length;s++){const a=e[s];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!i||a.fromTime<i.fromTime)&&(i=a)}if(!i){const i=e[e.length-1];if(t>i.toTime)return i}return i}_isLastRef(t){const e=this._currentRepresentation?.refs;if(!e)return!1;const i=e[e.length-1];return t.fromTime===i.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var ee;!function(t){t.STOPPED='stopped',t.MANIFEST_LOADED='manifest-loaded',t.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',t.METADATA_LOADED='metadata-loaded',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ee||(ee={}));const ie=[ee.PAUSED,ee.PLAYING];class se{videoState=new Y(ee.STOPPED);subscription=new i;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new ft;elementSize$=new t(void 0);dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new vt(this.video),this.dash=new te({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i,category:a.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',category:a.WTF,message:'DashProvider internal logic error',thrown:e})},o=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},h=Tt(this.video),p=(t,e)=>this.subscription.add(t.subscribe(e,i));p(h.timeUpdate$,t.position$),p(h.durationChange$,t.duration$),p(h.ended$,t.endedEvent$),p(h.looped$,t.loopedEvent$),p(h.error$,t.error$),p(h.isBuffering$,t.isBuffering$),p(h.playing$,t.firstFrameEvent$),p(h.canplay$,t.canplay$),this.subscription.add(h.seeking$.subscribe((()=>{r(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===ee.PLAYING||this.videoState.getState()===ee.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(h.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,h.volumeState$,i)),this.subscription.add(h.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,e.playbackRate,h.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),p(Ct(this.video),this.elementSize$),this.subscription.add(h.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY)}),i)).add(h.pause$.subscribe((()=>{this.videoState.setState(ee.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)}))).add(h.playing$.subscribe((()=>{this.videoState.setState(ee.PLAYING),M(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(h.loadedMetadata$.subscribe((()=>{this.videoState.setState(ee.METADATA_LOADED)}),i)).add(h.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(u((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,category:a.WTF,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(d(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,n(this.video,'progress')).pipe(u((()=>{const t=this.currentRepresentation$.getValue(),e=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.videoTrack.getState(),r=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),n=this.elementSize$.getValue(),d=o();let h;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&s(a))h=a;else{const i=Xt(this.video.buffered,1e3*this.video.currentTime),s=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(i/s,1);h=_t(e.map((({track:t})=>t)),{container:n,throughput:r,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:e.find((({representation:e})=>e===t))?.track})?.id}return s(h)?e.find((({track:t})=>t.id===h))?.representation:void 0})),l()).subscribe(this.currentRepresentation$,i)).add(g({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(v((t=>t.to===ee.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(v(s))}).pipe(S()).subscribe((()=>this.videoState.setState(ee.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(v(s),l(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&o()?t.height<=e.height:t===e))).subscribe((t=>{const e=Xt(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!o())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(It(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Jt(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(S(),b(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(v(s)).subscribe(this.handleRepresentationPlay,i)).add(d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return o(t)}}handleManifestReady=t=>{const e=[];for(const i of t){const t=i.name??i.id??i.height.toString(10),s=(i.name&&Ot(i.name))??H(i),a=i.bandwidth/1e3,r={width:i.width,height:i.height},n=i.fps;if(!s)continue;const o={id:t,quality:s,bitrate:a,size:r,fps:n};e.push({track:o,representation:i})}this.representations$.next(e),this.params.output.availableVideoTracks$.next(e.map((({track:t})=>t))),this.videoState.setState(ee.MANIFEST_LOADED)};handleRepresentationPlay=t=>{const e=this.representations$.getValue().find((({representation:e})=>e===t))?.track;if(e){this.params.output.currentVideoTrack$.next(e);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(e.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return p(t,'Can\'t select representation. something went wrong'),t};seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(ee.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)switch(s?.to!==P.PAUSED&&a.state===C.Requested&&ie.includes(t)&&this.seek(a.position,a.forcePrecise),t){case ee.STOPPED:return this.videoState.startTransitionTo(ee.MANIFEST_LOADED),void this.prepare();case ee.MANIFEST_LOADED:return void this.videoState.startTransitionTo(ee.INITIAL_REPRESENTATION_SELECTED);case ee.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(ee.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case ee.METADATA_LOADED:return this.videoState.startTransitionTo(ee.READY),void this.dash.updateRefsForCurrentTime();case ee.READY:return void(i===P.PAUSED?(this.videoState.setState(ee.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()));case ee.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):s?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case ee.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):s?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}else t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ee.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0))}}var ae,re,ne,oe,de;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(ae||(ae={})),function(t){t.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',t.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(re||(re={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(ne||(ne={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(oe||(oe={})),function(t){t.MP4='mp4',t.WEBM='webm'}(de||(de={}));var he=(t,e)=>{for(let i=0;i<t.length;i++){if(1e3*t.start(i)<=e&&1e3*t.end(i)>e)return!0}return!1};const ue='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;let ce=!1;try{ce=bt()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??'',10)<16}catch(t){console.error(t)}class le{bufferFull$=new e;error$=new e;buffer;queue=[];currentTask=null;destroyed=!1;constructor(t){this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const a={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(a),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=ce&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}completeTask=()=>{try{if(this.currentTask){const t=this.currentTask.signal?.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',category:a.VIDEO_PIPELINE,message:'Buffer appending or removal failed',thrown:t})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(t.signal?.aborted)return t.callback(!1),void this.pull();this.currentTask=t;const{operation:e}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===e?this.bufferFull$.next(this.currentTask.data.byteLength):t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===e||this.error$.next({id:`BufferTaskQueue:${e}`,category:a.VIDEO_PIPELINE,message:'Buffer operation failed',thrown:t}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(t){const{operation:e}=t;switch(e){case'append':this.buffer.appendBuffer(t.data);break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(t.init);break;default:o(e)}}}var pe,me=t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(pe||(pe={}));class fe{throughputEstimator;requestQuic;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new et;subscription=new i;constructor({throughputEstimator:t,requestQuic:e}){this.throughputEstimator=t,this.requestQuic=e}onHeadersReceived(t){const{type:e,reused:i}=Jt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest=E(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=dt(e));const i=yield tt(e,{signal:this.abortAllController.signal}).catch(ge);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=E(this.abortAllController.signal,async function*(t,{rangeMethod:e=pe.HEADER,range:i,onProgress:s,priority:a='auto',signal:r,measureThroughput:h=!0}={}){let u=t;const c=new Headers;if(i)switch(e){case pe.HEADER:c.append('Range',`${i.from}-${i.to}`);break;case pe.PARAM:{const t=new URL(u,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),u=t.toString();break}default:o(e)}this.requestQuic&&(u=dt(u));let l=this.abortAllController.signal;if(r){const t=new et;if(this.subscription.add(d(n(this.abortAllController.signal,'abort'),n(r,'abort')).subscribe((()=>{try{t.abort()}catch(t){ge(t)}}))),this.abortAllController.signal.aborted||r.aborted)try{t.abort()}catch(t){ge(t)}l=t.signal}const p=y(),m=yield tt(u,{priority:a,headers:c,signal:l}).catch(ge),f=y();if(this.throughputEstimator?.addRawRtt(f-p),!m)return null;if(!m.ok||!m.body)return Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));this.onHeadersReceived(m.headers);const g=parseInt(m.headers.get('Content-Length')??'',10)||i&&i.to-i.from+1||NaN;if(!g){const t=yield m.arrayBuffer();return this.throughputEstimator?.addRawSpeed(t.byteLength,y()-f),s?.(new DataView(t),t.byteLength),t}if(!s&&!h)return m.arrayBuffer();const[S,b]=m.body.tee(),v=S.getReader();h&&this.throughputEstimator?.trackStream(b);let T=0;const w=new ArrayBuffer(g),$=new Uint8Array(w),k=new DataView(w);let A=!1;const P=t=>{A=!0,ge(t)},R=E(l,async function*({done:t,value:e}){0===T&&this.lastRequestFirstBytes$.next(y()-p),l.aborted||(t?s?.(k,T):e&&($.set(e,T),T+=e.byteLength,s?.(k,T),yield v?.read().then(R,P)))}.bind(this));return yield v?.read().then(R,P),A?null:w}.bind(this));async fetchRepresentation(t,e,i='auto'){const{type:s}=t;switch(s){case ne.BYTE_RANGE:return await this.fetchByteRangeRepresentation(t,e,i)??null;case ne.TEMPLATE:return await this.fetchTemplateRepresentation(t,i)??null;default:o(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=E(this.abortAllController.signal,async function*(t,e,i){if(t.type!==ne.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,n,o=s,d=a,h=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,h=a+1===r,h&&(o=Math.min(r,s),d=Math.max(n,a))),o=Math.min(o,0);const u=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!u)return null;const c=new DataView(u,s-o,a-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(h&&void 0!==r&&void 0!==n)p=new DataView(u,r-o,n-r+1);else{const s=e.getIndexRange(l);if(s){const e=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,l);return{dataView:new DataView(u),segments:m}}.bind(this));fetchTemplateRepresentation=E(this.abortAllController.signal,async function*(t,e){if(t.type!==ne.TEMPLATE)return null;const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield this.fetch(i,{priority:e,measureThroughput:!1});if(!s)return null;return{segments:t.segments.map((t=>({...t,status:oe.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this))}const ge=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Se=new TextDecoder('ascii'),be=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=Se.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},ve={validateData:t=>'ftyp'===Se.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=be(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),d=4294967295&a();let h=n/r*1e3,u=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=a(),e=t>>>31,s=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;i.push({status:oe.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=be(a);if(s||='mdat'===i.id,!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var ye,Te;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(ye||(ye={})),function(t){t.SignedInteger='int',t.UnsignedInteger='uint',t.Float='float',t.String='string',t.UTF8='utf8',t.Date='date',t.Master='master',t.Binary='binary'}(Te||(Te={}));const Ee={[ye.EBML]:{type:Te.Master},[ye.EBMLVersion]:{type:Te.UnsignedInteger},[ye.EBMLReadVersion]:{type:Te.UnsignedInteger},[ye.EBMLMaxIDLength]:{type:Te.UnsignedInteger},[ye.EBMLMaxSizeLength]:{type:Te.UnsignedInteger},[ye.DocType]:{type:Te.String},[ye.DocTypeVersion]:{type:Te.UnsignedInteger},[ye.DocTypeReadVersion]:{type:Te.UnsignedInteger},[ye.Void]:{type:Te.Binary},[ye.Segment]:{type:Te.Master},[ye.SeekHead]:{type:Te.Master},[ye.Seek]:{type:Te.Master},[ye.SeekID]:{type:Te.Binary},[ye.SeekPosition]:{type:Te.UnsignedInteger},[ye.Info]:{type:Te.Master},[ye.TimestampScale]:{type:Te.UnsignedInteger},[ye.Duration]:{type:Te.Float},[ye.Tracks]:{type:Te.Master},[ye.Chapters]:{type:Te.Master},[ye.Cluster]:{type:Te.Master},[ye.Timestamp]:{type:Te.UnsignedInteger},[ye.SilentTracks]:{type:Te.Master},[ye.SilentTrackNumber]:{type:Te.UnsignedInteger},[ye.Position]:{type:Te.UnsignedInteger},[ye.PrevSize]:{type:Te.UnsignedInteger},[ye.SimpleBlock]:{type:Te.Binary},[ye.BlockGroup]:{type:Te.Master},[ye.EncryptedBlock]:{type:Te.Binary},[ye.Attachments]:{type:Te.Master},[ye.Tags]:{type:Te.Master},[ye.Cues]:{type:Te.Master},[ye.CuePoint]:{type:Te.Master},[ye.CueTime]:{type:Te.UnsignedInteger},[ye.CueTrackPositions]:{type:Te.Master},[ye.CueTrack]:{type:Te.UnsignedInteger},[ye.CueClusterPosition]:{type:Te.UnsignedInteger},[ye.CueRelativePosition]:{type:Te.UnsignedInteger},[ye.CueDuration]:{type:Te.UnsignedInteger},[ye.CueBlockNumber]:{type:Te.UnsignedInteger},[ye.CueCodecState]:{type:Te.UnsignedInteger},[ye.CueReference]:{type:Te.Master},[ye.CueRefTime]:{type:Te.UnsignedInteger}},we=t=>{const e=t.getUint8(0);let i=0;128&e?i=1:64&e?i=2:32&e?i=3:16&e&&(i=4);const s=$e(t,i),a=s in Ee,r=a?Ee[s].type:Te.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),h=((n&255>>o)<<8*(o-1))+$e(d),u=i+o;let c;return c=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:u,tagSize:u+h,value:c,valueSize:h}},$e=(t,e=t.byteLength)=>{switch(e){case 1:return t.getUint8(0);case 2:return t.getUint16(0);case 3:return t.getUint16(0)<<8|t.getUint8(2);case 4:return t.getUint32(0);case 5:return t.getUint32(0)<<8|t.getUint8(4);case 6:return t.getUint32(0)<<16|t.getUint16(4);case 7:return t.getUint32(0)<<32|t.getUint16(4)<<8|t.getUint8(6);case 8:return t.getUint32(0)<<32|t.getUint32(4)}return 0},ke=(t,e)=>{switch(e){case Te.SignedInteger:return t.getInt8(0);case Te.UnsignedInteger:return $e(t);case Te.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Te.String:return new TextDecoder('ascii').decode(t);case Te.UTF8:return new TextDecoder('utf-8').decode(t);case Te.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Te.Master:case Te.Binary:return t;default:o(e)}},Ae=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=we(s);if(!e(a))return;a.type===Te.Master&&Ae(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},Pe=[ye.Info,ye.SeekHead,ye.Tracks,ye.Chapters,ye.Cluster,ye.Cues,ye.Attachments,ye.Tags],Re=[ye.Timestamp,ye.SilentTracks,ye.SilentTrackNumber,ye.Position,ye.PrevSize,ye.SimpleBlock,ye.BlockGroup,ye.EncryptedBlock],De={validateData:t=>{if(t.getUint32(0)!==ye.EBML)return!1;let e,i,s;const a=we(t);return Ae(a.value,(({tag:t,type:a,value:r})=>(t===ye.EBMLReadVersion?e=ke(r,a):t===ye.DocType?i=ke(r,a):t===ye.DocTypeReadVersion&&(s=ke(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,a,r,n,o=!1,d=!1,h=!1;return Ae(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===ye.SeekID){const t=ke(c,u);n=$e(t)}else t!==ye.SeekPosition&&(n=void 0);return t===ye.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===ye.Info?o=!0:t===ye.SeekHead?d=!0:t===ye.TimestampScale?s=ke(c,u):t===ye.Duration?a=ke(c,u):t===ye.SeekPosition&&n===ye.Cues?r=ke(c,u):o&&d&&Pe.includes(t)&&(h=!0),!h})),p(e,'Failed to parse webm Segment start'),p(i,'Failed to parse webm Segment end'),p(a,'Failed to parse webm Segment duration'),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:r}},getIndexRange:t=>{if(r(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,a=!1;const r=t=>s(t.time)&&s(t.position),n=[];let o;return Ae(t,(({tag:t,type:e,value:s})=>{switch(t){case ye.Cues:i=!0;break;case ye.CuePoint:o&&r(o)&&n.push(o),o={};break;case ye.CueTime:o&&(o.time=ke(s,e));break;case ye.CueTrackPositions:break;case ye.CueClusterPosition:o&&(o.position=ke(s,e));break;default:i&&Pe.includes(t)&&(a=!0)}return!(i&&a)})),o&&r(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:a}=t,r=n[i+1];return{status:oe.NONE,time:{from:s,to:r?r.time:e.segmentDuration},byte:{from:e.segmentStart+a,to:r?e.segmentStart+r.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Ae(t,(s=>s.tag===ye.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Re.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||=[ye.SimpleBlock,ye.BlockGroup,ye.EncryptedBlock].includes(s.tag)),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class _e{onLastSegment$=new t(!1);fullyBuffered$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;gaps=[];subscription=new i;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new et;destroyAbortController=new et;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;constructor(t,e,i,s,{fetcher:a,tuning:r,getCurrentPosition:n}){switch(this.fetcher=a,this.tuning=r,this.forwardBufferTarget=r.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.container=i,i){case de.MP4:this.containerParser=ve;break;case de.WEBM:this.containerParser=De;break;default:o(i)}this.initData=new Map(s.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(s.map((t=>[t.id,t]))),this.kind=t,this.mediaSource=e,this.sourceBuffer=null}startWith=E(this.destroyAbortController.signal,async function*(t){const e=this.representations.get(t);p(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new le(this.sourceBuffer),this.subscription.add(n(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',category:a.WTF,message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(n(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',category:a.VIDEO_PIPELINE,message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>{if(!this.sourceBuffer)return;const e=Math.min(this.bufferLimit,me(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield this.loadInit(e,'high',!0);const i=this.initData.get(e.id),r=this.segments.get(e.id);if(p(i,'No init buffer for starting representation'),p(r,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let o=0;for(const t of r)t.time.from-o>=300&&this.gaps.push({representation:e.id,from:o,to:t.time.from}),o=t.time.to;s(e.duration)&&e.duration-o>=300&&this.gaps.push({representation:e.id,from:o,to:e.duration}),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=E(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;this.switchingToRepresentationId=t;const e=this.representations.get(t);p(e,`No such representation ${t}`);let i=this.initData.get(t);if(r(i)?yield this.loadInit(e,'high',!1):i instanceof Promise&&(yield i),i=this.initData.get(t),!(i&&i instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal);const a=this.getCurrentPosition();s(a)&&this.maintain(a)}.bind(this));abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(t){if(r(this.downloadingRepresentationId)||r(this.playingRepresentationId)||r(this.sourceBuffer))return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(p(e,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find((e=>t>=e.time.from&&t<e.time.to));let a=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,i=Xt(this.sourceBuffer.buffered,t),r=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(a=r)}if(isFinite(this.bufferLimit)&&me(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),s&&s.status!==oe.NONE))return;let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,e.segmentReference.type,a),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&s)if(n.includes(s))t='high';else{const e=n.at(0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===oe.FED&&!n.length&&Xt(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=i.at(-1);o&&o.status===oe.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){const e=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!e)return;const i=this.segments.get(e);if(!i)return;return i.find((e=>e.time.from<=t&&e.time.to>=t))?.time.from??void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===oe.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==ne.BYTE_RANGE)return t.slice(s,s+1);const a=t;let r=0;const n=[];for(let t=s;t<a.length&&r<=this.tuning.dash.segmentRequestSize;t++){const e=a[t];if(r+=e.byte.to+1-e.byte.from,e.status!==oe.NONE&&e.status!==oe.PARTIALLY_EJECTED)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,r,n=t;const{type:d}=e.segmentReference;switch(d){case ne.BYTE_RANGE:s=e.segmentReference.url,r={from:t.at(0).byte.from,to:t.at(-1).byte.to};break;case ne.TEMPLATE:{const i=t.at(0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),n=[i];break}default:o(d)}for(const t of n)t.status=oe.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:e.id});const{signal:h}=this.downloadAbortController;if(this.failedDownloads&&(await E(h,async function*(){const t=w(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))(),h.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(s,{rangeMethod:pe.PARAM,range:r,onProgress:(t,i)=>{if(!h.aborted)try{this.onSomeDataLoaded(t,e.id,r?r.from:0,i,h)}catch(t){this.error$.next({id:'SegmentFeeding',category:a.VIDEO_PIPELINE,message:'Error when feeding segments',thrown:t})}},signal:h,priority:i}).then((()=>this.failedDownloads=0),(e=>{for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.onSegmentDownloadError(e)}))}onSegmentDownloadError(t){let e=!1;const i=this.getCurrentPosition();if(this.sourceBuffer&&s(i)){e=Xt(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,e||this.error$.next({id:'SegmentDownload',category:a.NETWORK,message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,a){if(!this.activeSegments.size)return;const r=t=>{this.abortSegment(t.segment)},n=t=>{this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=oe.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const i of this.representations.values())if(i.id!==e)for(const e of this.segments.get(i.id)??[])e.status===oe.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=oe.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,h=t.byteLength;for(const o of this.activeSegments){const{segment:u}=o,c=d===ne.BYTE_RANGE,l=c?u.byte.to-u.byte.from+1:h;if(o.representationId!==e)continue;if(!(!c||u.byte.from>=i&&u.byte.to<i+t.byteLength))continue;if(a.aborted){r(o);continue}const p=c?u.byte.from-i:0,m=p<s,f=(c?u.byte.to-i:t.byteLength)<=s;if(u.status===oe.DOWNLOADING&&m&&f){u.status=oe.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,l);this.sourceBufferTaskQueue.append(e,a).then((t=>t&&!a.aborted?n(o):r(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(l,s-p),o.loadedBytes>o.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),i=o.loadedBytes===l?e:this.containerParser.parseFeedableSegmentChunk(e);i?.byteLength&&(u.status=oe.PARTIALLY_FED,o.feedingBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,a).then((t=>{if(a.aborted)r(o);else if(t)o.fedBytes+=i.byteLength,o.fedBytes===l&&n(o);else{if(o.feedingBytes<l)return;r(o)}})))}}}abortSegment(t){t.status===oe.PARTIALLY_FED||t.status===oe.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=oe.NONE)),t.status=oe.PARTIALLY_EJECTED):t.status=oe.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const a=s instanceof Promise;e||=a,null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=ue((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,e='auto',i=!1){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',r=(!i&&this.failedDownloads>0?E(this.destroyAbortController.signal,async function*(){const t=w(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s))).then((e=>{if(!e)return;const{dataView:i,segments:s}=e,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,a),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',category:a.WTF,message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,r),r}async pruneBuffer(t){const e=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||r(e))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let s=0,a=1/0,n=-1/0,o=!1;const d=t=>{a=Math.min(a,t.time.from),n=Math.max(n,t.time.to);const e='size'in t?t.size??0:t.byte.to-t.byte.from;s+=e};for(const a of i){if(a.time.to>=e||s>=t)break;a.status===oe.FED&&d(a)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const a of i){if(a.time.from<e+this.forwardBufferTarget||s>t)break;a.status===oe.FED&&d(a)}}if(o=isFinite(a)&&isFinite(n),!o)for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=1e3*this.sourceBuffer.buffered.end(t);for(const t of i)if(t.status===oe.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(s)){a=e,n=s;break}}return o=isFinite(a)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(a,n)}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),e=t instanceof ArrayBuffer?t:void 0;this.sourceBufferTaskQueue.abort(e)}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ue((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',category:a.WTF,message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(r(this.sourceBuffer)||r(this.playingRepresentationId))return;const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const i=Math.round(1e3*this.sourceBuffer.buffered.start(e)),s=Math.round(1e3*this.sourceBuffer.buffered.end(e));t.push({from:i,to:s})}for(const e of this.segments.values())for(const i of e){const{status:e}=i;if(e!==oe.FED&&e!==oe.PARTIALLY_EJECTED)continue;const s=Math.round(i.time.from),a=Math.round(i.time.to),r=t.some((t=>t.from<=s&&t.to>=a)),n=t.some((t=>s>t.from&&s<t.to||a>t.from&&a<t.to));r||(i.status=n?oe.PARTIALLY_EJECTED:oe.NONE)}}}const Ie=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===i?.[1]?-1:1;return 24*e(i?.[5],s)*60*60*1e3+60*e(i?.[6],s)*60*1e3+60*e(i?.[7],s)*1e3+1e3*e(i?.[8],s)},Ce=(t,e)=>{let i=t;i=i.replaceAll('$$','$');const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[t,e]of Object.entries(s)){const s=new RegExp(`\\$${t}(?:%0(\\d+)d)?\\$`,'g');i=i.replaceAll(s,((t,i)=>r(e)?t:r(i)?e:e.padStart(parseInt(i,10),'0')))}return i},Le=['timeupdate','progress','play','seeked','stalled'];var xe,Ne;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(xe||(xe={}));class Be{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new i;fetcher;state$=new Y(xe.NONE);currentVideoRepresentation$=new t(void 0);error$=new e;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);forceEnded$=new e;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new et;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new fe({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=E(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(xe.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',category:a.NETWORK,message:'Failed to load manifest',thrown:t})));if(!i)return null;let r;try{r=((t,e)=>{const i={video:[],audio:[],text:[]},a=(new DOMParser).parseFromString(t,'application/xml').children[0],r=a.getElementsByTagName('Period')[0],n=r.children;let o;const d=a.getAttribute('mediaPresentationDuration'),h=r.getAttribute('duration');if(d)o=Ie(d);else if(h){const t=Ie(h);s(t)&&(o=t)}let u=0;const c=a.getAttribute('profiles')?.split(',')??[],l=c.includes(re.WEBM_AS_IN_FFMPEG)||c.includes(re.WEBM_AS_IN_SPEC)?de.WEBM:de.MP4;for(const t of n){const s=t.getAttribute('mimeType'),a=t.getAttribute('codecs'),r=t.getAttribute('contentType')??s?.split('/')[0],n=t.getAttribute('profiles')?.split(',')??[],d=t.querySelectorAll('Representation');if('text'!==r)for(const h of d){const d=h.getAttribute('mimeType')??s,l=h.getAttribute('codecs')??a??'',p=h.getAttribute('contentType')??d?.split('/')[0]??r,m=t.getAttribute('profiles')?.split(',')??[],f=parseInt(h.getAttribute('width')??'',10),g=parseInt(h.getAttribute('height')??'',10),S=parseInt(h.getAttribute('bandwidth')??'',10)/1e3,b=h.getAttribute('frameRate')??'',v=h.getAttribute('quality')??void 0,y=b?Et(b):void 0,T=`${h.getAttribute('id')??(u++).toString(10)}@${'video'===p?`${g}p`:'audio'===p?`${S}Kbps`:l}`,E=h.querySelector('BaseURL')?.textContent?.trim()??'',w=new URL(E,e).toString(),$=[...c,...n,...m];let k;const A=h.querySelector('SegmentBase'),P=h.querySelector('SegmentTemplate');if(A){const t=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[r,n]=a?a.split('-').map((t=>parseInt(t,10))):[],o=a?{from:r,to:n}:void 0;k={type:ne.BYTE_RANGE,url:w,initRange:s,indexRange:o}}else{if(!P)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:h.getAttribute('id')??void 0,bandwidth:h.getAttribute('bandwidth')??void 0},e=parseInt(P.getAttribute('timescale')??'',10),i=P.getAttribute('initialization')??'',s=P.getAttribute('media'),a=parseInt(P.getAttribute('startNumber')??'',10)??1,r=Ce(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const n=P.querySelectorAll('SegmentTimeline S')??[],o=[];let d=a,u=0;for(const i of n){const a=1e3*parseInt(i.getAttribute('d')??'',10),r=parseInt(i.getAttribute('r')??'',10)||0,n=parseInt(i.getAttribute('t')??'',10)??void 0;for(let i=0;i<r+1;i++){const i=Ce(s,{...t,segmentNumber:d.toString(10),segmentTime:n.toString(10)}),r=n?n/e:u;u+=a/e;const h=u;d++,o.push({time:{from:r,to:h},url:i})}}k={type:ne.TEMPLATE,baseUrl:w,initUrl:r,segments:o}}}if(!p||!d)continue;const R={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[p];R&&i[R].push({id:T,kind:R,segmentReference:k,profiles:$,duration:o,bitrate:S,mime:d,codecs:l,width:f,height:g,fps:y,quality:v})}}return{duration:o,container:l,representations:i}})(i??'',e)}catch(t){this.error$.next({id:'ManifestParsing',category:a.PARSER,message:'Failed to parse MPD manifest',thrown:t})}if(!r)return null;const n=({mime:e,codecs:i})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${i}"`));return this.manifest={...r,representations:Object.fromEntries(Object.entries(r.representations).map((([t,e])=>[t,e.filter(n)])))},this.manifest.representations.video.length?this.state$.setState(xe.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',category:a.PARSER,message:'No playable video representations'}),this.manifest}.bind(this));initRepresentations=E(this.destroyController.signal,async function*(t,e){p(this.manifest),p(this.element),this.state$.startTransitionTo(xe.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new _e(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new _e(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const r=d(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(u((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),o=d(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(u((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(d(this.forceEnded$,g({allBuffersFull:r,someBufferEnded:o}).pipe(v((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{this.source?.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',category:a.VIDEO_PIPELINE,message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(d(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>this.source?.addEventListener('sourceopen',t)))),s(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s(e)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)]):yield this.videoBufferManager.startWith(t),this.state$.setState(xe.REPRESENTATION_SELECTED),p(this.element),this.subscription.add(d(...Le.map((t=>n(this.element,t))),n(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',category:a.WTF,message:'Internal logic error',thrown:t})}))),this.subscription.add(n(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(n(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&he(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this));async switchRepresentation(t,e){return{[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[t]?.switchTo(e)}seek(t,e){let i;p(this.element),p(this.videoBufferManager),i=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(this.videoBufferManager.findSegmentStartTime(t)??t,this.audioBufferManager?.findSegmentStartTime(t)??t),he(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(xe.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager?.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager?.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=$(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',category:a.WTF,message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=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'}(Ne||(Ne={}));const Oe=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?Ot(r):void 0)??H({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Me=(t,e,i)=>{const s=e.indexOf(i);return t.at(Math.round(t.length*s/e.length))??t.at(-1)};class Ue{subscription=new i;videoState=new Y(Ne.STOPPED);video;player;params;elementSize$=new t(void 0);textTracksManager=new ft;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Dt;constructor(t){this.params=t,this.video=gt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Be({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=Tt(this.video),r=e=>{t.error$.next({id:'DashVKProvider',category:a.WTF,message:'DashVKProvider internal logic error',thrown:e})},o=(t,e)=>this.subscription.add(t.subscribe(e,r));o(i.timeUpdate$,t.position$),o(i.durationChange$,t.duration$),o(i.ended$,t.endedEvent$),o(i.looped$,t.loopedEvent$),o(i.error$,t.error$),o(i.isBuffering$,t.isBuffering$),o(i.currentBuffer$,t.currentBuffer$),o(i.playing$,t.firstFrameEvent$),o(i.canplay$,t.canplay$),o(this.player.error$,t.error$),o(this.player.lastConnectionType$,t.httpConnectionType$),o(this.player.lastConnectionReused$,t.httpConnectionReused$),o(this.player.lastRequestFirstBytes$.pipe(v(s),S(),b(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(ct(this.video,e.isLooped,r)),this.subscription.add(lt(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,e.playbackRate,i.playbackRateState$,r)),o(Ct(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Ne.PLAYING),M(e.playbackState,P.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(Ne.PAUSED),M(e.playbackState,P.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Ne.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(v((({to:t})=>t===xe.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Ne.READY)})));const h=e=>t.error$.next({id:'RepresentationSwitch',category:a.WTF,message:'Switching representations threw',thrown:e});this.subscription.add(d(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,n(this.video,'progress')).subscribe((()=>{const i=this.player.state$.getState(),s=this.player.state$.getTransition();if(i===xe.NONE||!this.videoTracks.length)return;const a=i===xe.MANIFEST_LOADED&&!s,r=i===xe.REPRESENTATION_SELECTED&&!s,n=e.autoVideoTrackSwitching.getState(),o=e.videoTrack.getState(),d=this.videoTracks.find((({track:{id:t}})=>t===o))?.track,u=t.currentVideoTrack$.getValue(),c=Xt(this.video.buffered,1e3*this.video.currentTime),l=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(c/Math.min(l,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),f=Math.max(d&&!n?this.audioRepresentations.get(d.id)?.bitrate??0:0,u?this.audioRepresentations.get(u.id)?.bitrate??0:0),g=_t(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),reserve:f,forwardBufferHealth:m,current:u,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=n?g??d:d??g;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(n),this.player.setBufferTarget(l)),a){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;p(t),this.player.initRepresentations(t.id,this.audioRepresentations.get(t.id)?.id)}else if(r){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(ae.VIDEO,t.id).catch(h),e&&this.player.switchRepresentation(ae.AUDIO,e.id).catch(h)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(l(),u((t=>t&&this.videoTracks.find((({representation:{id:e}})=>e===t))?.track))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const f=d(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(f.subscribe(this.syncPlayback,r))}async prepare(){const t=await this.player.initManifest(this.video,this.params.source.url);if(!t)return;this.videoTracks=[];const e=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),i=Array.from(t.representations.video).sort(((t,e)=>e.bitrate-t.bitrate));for(const t of i){const s=Oe(t);if(s){this.videoTracks.push({track:s,representation:t});const a=Me(e,i,t);a&&this.audioRepresentations.set(t.id,a)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(s.state===C.Requested&&i?.to!==P.PAUSED&&t!==Ne.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===Ne.STOPPED)return this.videoState.startTransitionTo(Ne.READY),void this.prepare();switch(t){case Ne.READY:return void(e===P.PAUSED?(this.videoState.setState(Ne.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Ne.PLAYING),this.playIfAllowed()));case Ne.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Ne.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case Ne.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Ne.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}else t!==Ne.STOPPED&&(this.videoState.startTransitionTo(Ne.STOPPED),this.player.stop(),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ne.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Ne.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Ve={};var Fe;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Fe||(Fe={}));const qe=(t,e)=>new T((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class He{subscription=new i;videoState=new Y(Fe.INITIALIZING);video;params;hls;textTracksManager=new ft;trackLevels=new Map;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(It(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',category:a.NETWORK,message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(Ve.Hls=e.default,Ve.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){p(Ve.Hls,'hls.js not loaded'),this.hls=new Ve.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Fe.STOPPED)}subscribe(){p(Ve.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',category:a.WTF,message:'HlsJsProvider internal logic error',thrown:t})},n=Tt(this.video),o=(t,e)=>this.subscription.add(t.subscribe(e,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.currentBuffer$,e.currentBuffer$),o(n.loadStart$,e.firstBytesEvent$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.seeked$,e.seekedEvent$),this.subscription.add(ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,t.playbackRate,n.playbackRateState$,i)),this.subscription.add(qe(this.hls,Ve.Events.ERROR).subscribe((t=>{t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),category:a.WTF,message:`HlsJs fatal ${t.type} ${t.details}, ${t.err?.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(n.playing$.subscribe((()=>{this.videoState.setState(Fe.PLAYING),M(t.playbackState,P.PLAYING)}),i)).add(n.pause$.subscribe((()=>{this.videoState.setState(Fe.PAUSED),M(t.playbackState,P.PAUSED)}),i)).add(n.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Fe.READY&&this.videoState.setState(Fe.READY),this.videoState.getState()===Fe.PLAYING&&this.playIfAllowed()}),i)),o(qe(this.hls,Ve.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{const i=e.name||e.height.toString(10),{width:s,height:a}=e,r=Ot(e.attrs.QUALITY??'')??H({width:s,height:a});if(!r)return t;const n=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,o={id:i.toString(),quality:r,bitrate:e.bitrate/1e3,size:{width:s,height:a},fps:n};return this.trackLevels.set(i,{track:o,level:e}),t.push(o),t}),[])))),e.availableVideoTracks$),o(qe(this.hls,Ve.Events.LEVEL_LOADING).pipe(u((({url:t})=>It(t)))),e.hostname$),this.subscription.add(ut(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const h=t=>Array.from(this.trackLevels.values()).find((({level:e})=>e===t))?.track,l=qe(this.hls,Ve.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>h(this.hls.levels[t]))));l.pipe(v(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(ut(t.videoTrack,(()=>h(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(r(t))return;const e=this.trackLevels.get(t)?.level;if(!e)return;const i=this.hls.levels.indexOf(e),s=this.hls.currentLevel,a=this.hls.levels[s];!a||e.bitrate>a.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:l.pipe(u((t=>t?.id))),onError:i})),o(n.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const f=d(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(f.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(t!==Fe.INITIALIZING)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case Fe.STOPPED:break;case Fe.READY:case Fe.PLAYING:case Fe.PAUSED:this.stop();break;default:o(t)}break;case P.PLAYING:switch(t){case Fe.PLAYING:break;case Fe.STOPPED:this.prepare();break;case Fe.READY:case Fe.PAUSED:this.playIfAllowed();break;default:o(t)}break;case P.PAUSED:switch(t){case Fe.PAUSED:break;case Fe.STOPPED:this.prepare();break;case Fe.READY:this.videoState.setState(Fe.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED);break;case Fe.PLAYING:this.pause();break;default:o(t)}break;default:o(e)}};prepare(){this.videoState.startTransitionTo(Fe.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Fe.PLAYING);await Mt(this.video)||(this.videoState.setState(Fe.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Fe.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Fe.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)}}var Ge=async t=>{const e=await tt(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0};const Ye=t=>{let e=null;if(t.QUALITY&&(e=Ot(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=H({width:i,height:s})}return e??null},ze=async(t,e=t)=>{const i=await tt(t),s=(await i.text()).split('\n'),a=[];for(let t=0;t<s.length;t++){const i=s[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!i)continue;const r=Object.fromEntries(i[1].split(',').map((t=>t.split('=')))),n=r.QUALITY??`stream-${r.BANDWIDTH}`,o=Ye(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let u;if(r.RESOLUTION){const[t,e]=r.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(u={width:t,height:e})}const c=new URL(s[++t],e).toString();o&&a.push({id:n,quality:o,url:c,bandwidth:d,size:u,fps:h})}return a};var Qe,We,je;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Qe||(Qe={}));class Je{subscription=new i;videoState=new Y(Qe.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);maxSeekBackTime$;liveOffset=new St;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),ze(O(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',category:a.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(It(this.params.source.url)),this.maxSeekBackTime$=new t(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',category:a.WTF,message:'HlsLiveProvider internal logic error',thrown:e})},r=Tt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(r.ended$,t.endedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadedMetadata$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Qe.PLAYING),M(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Qe.PAUSED),M(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Qe.READY&&this.videoState.setState(Qe.READY),this.videoState.getState()===Qe.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(l(),u((t=>-t/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(It(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Qe.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{const t=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(t||void 0)}),i)),this.subscription.add(g({startTime:this.manifestStartTime$.pipe(v(s)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,c(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(r(t))return;const e=O(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),Ge(e).then((t=>{if(r(t)){const t=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(r(t)||!isFinite(t))try{tt(e).then((t=>t.text())).then((t=>{const i=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(t)?.[1];if(i){const t=new URL(i,e).toString();Ge(t).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Qe.PAUSED),this.liveOffset.pause(),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Qe.STOPPED&&(this.videoState.startTransitionTo(Qe.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Qe.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===Qe.STOPPED)return this.videoState.startTransitionTo(Qe.READY),void this.prepare();if(s||a){const t=this.videoState.getState();return this.videoState.setState(Qe.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if(i?.to!==P.PAUSED&&r.state===C.Requested)return this.videoState.startTransitionTo(Qe.READY),this.seek(r.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Qe.READY:return void(e===P.PAUSED?(this.videoState.setState(Qe.PAUSED),this.liveOffset.pause(),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Qe.PLAYING),this.playIfAllowed()));case Qe.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Qe.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case Qe.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Qe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):i?.to===P.PAUSED&&(M(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Qe.CHANGING_MANIFEST:break;default:return o(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(We||(We={}));class Xe{subscription=new i;videoState=new Y(We.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video);const e={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([e]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(It(this.params.source.url)),ze(this.params.source.url).then((t=>{this.manifests$.next([e,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',category:a.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',category:a.WTF,message:'HlsProvider internal logic error',thrown:e})},r=Tt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadedMetadata$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(We.PLAYING),M(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(We.PAUSED),M(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===We.READY&&this.videoState.setState(We.READY),this.videoState.getState()===We.PLAYING&&this.playIfAllowed()}),i).add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(It(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===We.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===C.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();r(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(We.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==We.STOPPED&&(this.videoState.startTransitionTo(We.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(We.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===We.STOPPED)return this.videoState.startTransitionTo(We.READY),void this.prepare();if(s||a){const t=this.videoState.getState();this.videoState.setState(We.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case We.READY:return void(e===P.PAUSED?(this.videoState.setState(We.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(We.PLAYING),this.playIfAllowed()));case We.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(We.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case We.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(We.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));case We.CHANGING_MANIFEST:break;default:return o(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(je||(je={}));class Ke{subscription=new i;videoState=new Y(je.STOPPED);video;trackUrls={};params;textTracksManager=new ft;constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',category:a.WTF,message:'MpegProvider internal logic error',thrown:e})},r=Tt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadedMetadata$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(je.PLAYING),M(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(je.PAUSED),M(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===je.READY&&this.videoState.setState(je.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&s(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===je.PLAYING&&this.playIfAllowed()}),i)),this.textTracksManager.connect(this.video,e,t);const o=d(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();p(t,'MpegProvider: track is not selected');let{url:e}=this.trackUrls[t];p(e,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(e=dt(e)),this.video.setAttribute('src',e),this.video.load(),this.params.output.hostname$.next(It(e))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(je.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==je.STOPPED&&(this.videoState.startTransitionTo(je.STOPPED),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(je.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(t===je.STOPPED)return this.videoState.startTransitionTo(je.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case je.READY:return void(e===P.PAUSED?(this.videoState.setState(je.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(je.PLAYING),this.playIfAllowed()));case je.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(je.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case je.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(je.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}}const Ze=['stun:videostun.mycdn.me:80'],ti=()=>null;class ei{options;ws=null;peerConnection=null;serverUrl='';streamKey='';stream=null;signalingType='JOIN';retryTimeout;retryCount=0;externalStartCallback=ti;externalStopCallback=ti;externalErrorCallback=ti;constructor(t,e){this.options=this.normalizeOptions(e);const i=t.split('/');this.serverUrl=i.slice(0,i.length-1).join('/'),this.streamKey=i[i.length-1]}onStart(t){try{this.externalStartCallback=t}catch(t){this.handleSystemError(t)}}onStop(t){try{this.externalStopCallback=t}catch(t){this.handleSystemError(t)}}onError(t){try{this.externalErrorCallback=t}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(t){this.handleSystemError(t)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(t){try{if(!this.ws)return;this.ws=null,t.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(t){try{this.externalErrorCallback(new Error(t.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(t){try{const e=this.parseMessage(t.data);switch(e.type){case'JOIN':case'CALL_JOIN':this.handleJoinMessage(e);break;case'UPDATE':this.handleUpdateMessage(e);break;case'STATUS':this.handleStatusMessage(e)}}catch(t){this.handleRTCError(t)}}handleJoinMessage(t){switch(t.inviteType){case'ANSWER':this.handleAnswer(t.sdp);break;case'CANDIDATE':this.handleCandidate(t.candidate)}}handleStatusMessage(t){switch(t.status){case'UNPUBLISHED':this.handleUnpublished()}}async handleUpdateMessage(t){try{const e=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(e),this.handleAnswer(t.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const t={iceServers:[{urls:Ze}]};this.peerConnection=new RTCPeerConnection(t),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const e=await this.createOffer();await this.peerConnection.setLocalDescription(e),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:e.sdp,callSupport:!1})}catch(t){this.handleRTCError(t)}}async handleAnswer(t){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:t}))}catch(t){this.handleRTCError(t)}}async handleCandidate(t){if(t)try{this.peerConnection&&await this.peerConnection.addIceCandidate(t)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(t){this.handleRTCError(t)}}handleSystemError(t){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',category:a.WTF,message:t.message})}async onPeerConnectionStream(t){const e=t.streams[0];this.stream&&this.stream.id===e.id||(this.stream=e,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(t){t.candidate&&this.send({type:this.signalingType,inviteType:'CANDIDATE',candidate:t.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const t=this.peerConnection.iceConnectionState;['failed','closed'].indexOf(t)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const t=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}),e=t.sdp||'';if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(e))throw new Error('No h264 codec support error');return t}handleRTCError(t){try{this.externalErrorCallback(t||new Error('RTC connection error'))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error('Network error'))}catch(t){this.handleSystemError(t)}}send(t){this.ws&&this.ws.send(JSON.stringify(t))}parseMessage(t){try{return JSON.parse(t)}catch(t){throw new Error('Can not parse socket message')}}closeConnections(){const t=this.ws;t&&(this.ws=null,t.close(1e3)),this.removePeerConnection()}removePeerConnection(){let t=this.peerConnection;t&&(this.peerConnection=null,t.close(),t.ontrack=null,t.onicecandidate=null,t.oniceconnectionstatechange=null,t=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),1e3)}normalizeOptions(t={}){const e={stunServerList:Ze,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var ii;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ii||(ii={}));class si{subscription;params;log;video;videoState=new Y(ii.STOPPED);liveStreamClient;maxSeekBackTime$=new t(0);constructor(t){this.subscription=new i,this.params=t,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=gt(t.container),this.liveStreamClient=new ei(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'WebRTCLiveProvider',category:a.WTF,message:'WebRTCLiveProvider internal logic error',thrown:e})};d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})}));const s=Tt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(s.timeUpdate$,t.liveTime$),r(s.ended$,t.endedEvent$),r(s.looped$,t.loopedEvent$),r(s.error$,t.error$),r(s.isBuffering$,t.isBuffering$),r(s.currentBuffer$,t.currentBuffer$),this.subscription.add(s.durationChange$.subscribe((e=>{t.duration$.next(e===1/0?0:e)}))).add(s.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ii.READY&&this.videoState.setState(ii.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(ii.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.videoState.setState(ii.PLAYING)}),i)).add(s.error$.subscribe(t.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(lt(this.video,e.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(t.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe((i=>{switch(i.to){case ii.STOPPED:t.position$.next(0),t.duration$.next(0),e.playbackState.setState(P.STOPPED);break;case ii.READY:break;case ii.PAUSED:e.playbackState.setState(P.PAUSED);break;case ii.PLAYING:e.playbackState.setState(P.PLAYING);break;default:return o(i.to)}}),i)).add(d(e.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i))}onLiveStreamStart(t){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:B.INVARIANT}),this.video.srcObject=t,M(this.params.desiredState.playbackState,P.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ii.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(t){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',category:a.EXTERNAL_API,message:t.message,thrown:t})}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(ii.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==ii.STOPPED&&(this.videoState.startTransitionTo(ii.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ii.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition();if(t===ii.STOPPED)return this.videoState.startTransitionTo(ii.READY),void this.prepare();if(s)this.prepare();else switch(t){case ii.READY:return void(e===P.PAUSED?(this.videoState.setState(ii.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(ii.PLAYING),this.playIfAllowed()));case ii.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(ii.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case ii.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(ii.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}}class ai{iterator;current;constructor(t){this.iterator=t[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const ri=bt(),ni=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),oi=document.createElement('video'),di={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(oi.canPlayType?.('application/x-mpegurl')||oi.canPlayType?.('vnd.apple.mpegURL')),webrtc:Boolean(window.RTCPeerConnection)},hi={mp4:Boolean(oi.canPlayType?.('video/mp4')),webm:Boolean(oi.canPlayType?.('video/webm'))},ui={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},ci=(ui.h264||ui.h265)&&ui.aac,li=!ri,pi=di.hls&&hi.mp4&&(ni||ri),mi=Boolean(window.WebSocket);const fi=2e4,gi=3,Si={cacheDuration:12e4},bi={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},vi={maxPausedTime:3e4},yi={maxPausedTime:3e4};class Ti{current$=new t({type:void 0});providerError$=new e;noAvailableProvidersError$=new e;providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,canplay$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)};subscription=new i;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:e}=this.params.tuning,i=e.length?[...t.screenFormatsPriority.filter((t=>!e.includes(t))),...t.screenFormatsPriority.filter((t=>e.includes(t)))]:t.screenFormatsPriority;this.screenFormatsIterator=new ai(((t,e=!1)=>t.filter((t=>{switch(t){case R.DASH:return di.mse&&hi.mp4&&ci&&li;case R.DASH_SEP:return di.mse&&hi.mp4&&ci;case R.DASH_WEBM:return di.mse&&hi.webm&&ui.vp9&&ui.opus;case R.DASH_LIVE:case R.DASH_ONDEMAND:return di.mse&&hi.mp4&&ci;case R.HLS:case R.HLS_LIVE:case R.HLS_ONDEMAND:return pi||e&&di.mse&&hi.mp4&&ci;case R.MPEG:return hi.mp4;case R.DASH_LIVE_WEBM:return!1;case R.WEB_RTC_LIVE:return di.webrtc&&mi&&ui.h264&&(hi.mp4||hi.webm);default:return o(t)}})))(i.filter((e=>s(t.sources[e]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new ai(t.chromecastFormatsPriority.filter((e=>s(t.sources[e]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),e=this.chooseFormat(t);if(r(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',category:a.WTF,message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const t=this.current$.getValue().destination;p(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case D.SCREEN:return this.createScreenProvider(e);case D.CHROMECAST:return this.createChromecastProvider(e);default:return o(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,a=this.providerOutput,r={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case R.DASH:{const i=this.applyFailoverHost(e[t]);return p(i),new se({...r,source:i,config:Si})}case R.DASH_SEP:case R.DASH_WEBM:case R.DASH_ONDEMAND:{const i=this.applyFailoverHost(e[t]);return p(i),this.params.tuning.useDashJs?new Bt({...r,source:i,format:t,config:yi}):new Ue({...r,source:i})}case R.HLS:case R.HLS_ONDEMAND:{const i=this.applyFailoverHost(e[t]);return p(i),pi||!this.params.tuning.useHlsJs?new Xe({...r,source:i}):new He({...r,source:i})}case R.HLS_LIVE:{const i=this.applyFailoverHost(e[t]);return p(i),new Je({...r,source:i,config:vi})}case R.MPEG:{const i=this.applyFailoverHost(e[t]);return p(i),new Ke({...r,source:i})}case R.DASH_LIVE:{const i=this.applyFailoverHost(e[t]);return p(i),new jt({...r,source:i,config:bi})}case R.WEB_RTC_LIVE:{const r=this.applyFailoverHost(e[t]);return p(r),new si({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case R.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return o(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:a}=this.params,r=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return p(n),new Q({connection:n,meta:a,container:i,source:e,format:t,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?D.CHROMECAST:D.SCREEN}chooseFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case D.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return o(t)}}skipFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.next();case D.CHROMECAST:return this.chromecastFormatsIterator.next();default:return o(t)}}handleNoFormatsError(t){switch(t){case D.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case D.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return o(t)}}applyFailoverHost(t){if(void 0===this.failoverIndex)return t;const e=this.params.failoverHosts[this.failoverIndex];if(!e)return t;const i=t=>{const i=new URL(t);return i.host=e,i.toString()};if(void 0===t)return t;if('type'in t){if('raw'===t.type)return t;if('url'===t.type)return{...t,url:i(t.url)}}return Object.fromEntries(Object.entries(t).map((([t,e])=>[t,i(e)])))}initProviderErrorHandling(){const t=new i;let s=!1,r=0;var n;return t.add(d(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:fi,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(v((({type:t})=>void 0!==t)))},new T((t=>{const s=new i,a=n.desiredPlaybackState$.stateChangeStarted$.pipe(u((({from:t,to:e})=>`${t}-${e}`))),r=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let h=0,c='unknown';return s.add(a.subscribe((t=>{h&&window.clearTimeout(h),c=t,h=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(r.subscribe((()=>{window.clearTimeout(h),c='provider change',h=0}))),s.add(o.subscribe((()=>{h&&(window.clearTimeout(h),h=window.setTimeout((()=>d.next(c)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(h),s.unsubscribe()}}))).pipe(u((t=>({id:`ProviderHangup:${t}`,category:a.WTF,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),t.add(this.current$.subscribe((()=>{s=!1;const e=this.params.desiredState.playbackState.transitionEnded$.pipe(v((({to:t})=>t===P.PLAYING)),S()).subscribe((()=>s=!0));t.add(e)}))),t.add(this.providerError$.subscribe((t=>{if(this.current$.getValue().destination===D.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>this.switchToNextProvider()),(()=>this.params.dependencies.chromecastInitializer.disconnect()));else{const e=t.category===a.NETWORK,i=this.params.failoverHosts.length>0&&(void 0===this.failoverIndex||this.failoverIndex<this.params.failoverHosts.length-1),n=r<gi;i&&(e&&s||!n)?(this.failoverIndex=void 0===this.failoverIndex?0:this.failoverIndex+1,this.reinitProvider()):n?(r++,this.reinitProvider()):this.switchToNextProvider()}}))),t}}const Ei=(t,e,i)=>i*e+(1-i)*t;class wi{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const i=e.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Pt(`raw_${i}`),this.smoothedSeries$=new Pt(`smoothed_${i}`),this.reportedSeries$=new Pt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=(this.pastMeasures[t]-this.smoothed)**2,i++);e/=i;const s=Math.sqrt(e),a=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=t,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(t),this.slow=Ei(this.slow,t,this.params.emaAlphaSlow),this.fast=Ei(this.fast,t,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>a||this.smoothed<n||(r(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}var $i;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}($i||($i={}));const ki=new Map;let Ai=$i.RUNTIME;const Pi=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Pi,'test'),localStorage.removeItem(Pi),Ai=$i.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Pi),Ai=$i.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Ai=$i.RUNTIME}}})();const Ri=(t,e)=>{switch(Ai){case $i.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case $i.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case $i.RUNTIME:return void ki.set(t,e);default:o(Ai)}},Di=window.navigator.connection,_i=()=>{const t=Di?.downlink;if(s(t)&&10!==t)return 1e3*t},Ii=()=>{const t=Di?.rtt;if(s(t)&&3e3!==t)return t},Ci=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Li{throughput;rtt;subscription=new i;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=Li.load('one_video_throughput')||(e.useBrowserEstimation?_i():void 0)||5e3,a=Li.load('one_video_rtt')??(e.useBrowserEstimation?Ii():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(Ci(i,a,e.rttPenaltyRequestSize)),this.throughput=new wi({initial:i,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new wi({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=_i();t&&this.throughput.next(t);const e=Ii();s(e)&&this.rtt.next(e)};Di&&'onchange'in Di&&this.subscription.add(n(Di,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Ri('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Ri('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(g({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>Ci(t,i,e.rttPenaltyRequestSize))),v((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(t){let e=0,s=y();const a=new i;switch(this.subscription.add(a),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:a.add(n(t,'progress').pipe(S()).subscribe((t=>{e=t.loaded,s=y()})));break;case 1:case 0:a.add(n(t,'loadstart').subscribe((()=>{e=0,s=y()})))}a.add(n(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,a=y(),r=t-e,n=a-s;this.addRawSpeed(r,n,1)}this.concurrentDownloads.delete(t),a.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=y();let a=0,r=y();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:d,value:h})=>{d?(this.addRawSpeed(i,y()-s,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,a+=h.byteLength,a>=this.tuningConfig.streamMinSampleSize&&y()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,y()-r,this.concurrentDownloads.size),a=0,r=y()),await(e?.read().then(o,n)))};this.concurrentDownloads.add(t),e?.read().then(o,n)}addRawSpeed(t,e,i=1){if(Li.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){const e=(t=>{switch(Ai){case $i.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case $i.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case $i.RUNTIME:return ki.get(t);default:o(Ai)}})(t);if(s(e))return parseInt(e,10)??void 0}}const xi={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}};const Ni=({playbackState:t,seekState:e,playbackAbort$:a,looped$:n,position$:o})=>new T((h=>{let c;const l=t.transitionEnded$.pipe(v((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=t.stateChangeEnded$.pipe(v((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),m=e.stateChangeEnded$.pipe(v((({to:e})=>e.state===C.Requested&&(t.getTransition()?.from??t.getState())===P.PLAYING))),f=e.stateChangeEnded$.pipe(v((({from:e,to:i})=>e.state===C.Applying&&i.state===C.None&&(t.getTransition()?.from??t.getState())===P.PLAYING))),g=d(l,f).pipe(u((()=>o.getValue())),v(s)),S=d(d(p,m,a),n).pipe(u((()=>o.getValue())),v(s));return(new i).add(g.subscribe((t=>{c=t}))).add(S.subscribe((t=>{if(r(c)||c===t)return;const e={from:c,to:t};c=void 0,h.next(e)})))})),Bi={[D.SCREEN]:{vod:[...pi?[R.HLS,R.HLS_ONDEMAND]:[],R.DASH_WEBM,R.DASH_SEP,R.DASH,R.DASH_ONDEMAND,...pi?[]:[R.HLS,R.HLS_ONDEMAND],R.MPEG],live:pi?[R.WEB_RTC_LIVE,R.HLS_LIVE,R.DASH_LIVE]:[R.WEB_RTC_LIVE,R.DASH_LIVE,R.HLS_LIVE]},[D.CHROMECAST]:{vod:[R.DASH_WEBM,R.DASH_SEP,R.DASH_ONDEMAND,R.HLS,R.HLS_ONDEMAND,R.MPEG],live:[R.HLS_LIVE]}};class Oi{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new k;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new Y(P.STOPPED),seekState:new Y({state:C.None}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({})};info={playbackState$:new t(P.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentPlaybackRate$:new t(1),currentBuffer$:new t({start:0,end:0}),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(_.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)};events={inited$:new e,started$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,canplay$:new e,log$:new e};experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:kt};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(xi)){const s=xi[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:a??s}return e})(t),this.chromecastInitializer=new L({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Li(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),r=`Player.${String(e)}`,n=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,category:a.WTF,message:n,thrown:t}),t}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return p(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new Ti({screenFormatsPriority:[...Bi[D.SCREEN].live,...Bi[D.SCREEN].vod],chromecastFormatsPriority:[...Bi[D.CHROMECAST].live,...Bi[D.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},failoverHosts:t.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t,!1),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){p(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setPlaybackRate(t){p(this.providerContainer);const e=this.providerContainer?.providerOutput.element$.getValue();return e&&(this.desiredState.playbackRate.setState(t),e.playbackRate=t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){return(void 0===t||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t)))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){p(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(r(t))return this.info.position$.getValue();const e=this.desiredState.seekState.getState(),i=e.state===C.None?void 0:e.position;return s(i)?i/1e3:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(d(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(u((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(v((()=>!this.isPlaybackStarted)),v((t=>t.to===P.PLAYING))).subscribe((()=>{this.isPlaybackStarted=!0,this.events.started$.next()}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case P.PAUSED:this.events.willPause$.next();break;case P.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=y(),this.events.inited$.next())}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===C.Requested?this.desiredState.seekState.setState({...t,state:C.Applying}):this.events.managedError$.next({id:`WillSeekIn${t.state}`,category:a.WTF,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())}))).add(e.current$.pipe(u((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(u((t=>t.destination)),l()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(u((t=>t.map((({quality:t})=>t)).sort(((t,e)=>G(t)?1:G(e)?-1:V(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(t?.quality),this.info.videoBitrate$.next(t?.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(l()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(l()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(l()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(u((t=>t?{start:t.from,end:t.to}:{start:0,end:0}))).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(u((t=>t.muted)),l()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(u((t=>t.volume)),l()).subscribe(this.info.volume$)).add((({seekState:t,position$:e})=>d(t.stateChangeEnded$.pipe(u((({to:t})=>t.state===C.None?void 0:(t.position??NaN)/1e3)),v(s)),e.pipe(v((()=>t.getState().state===C.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(d(e.providerOutput.endedEvent$.pipe(b(!0)),e.providerOutput.seekedEvent$.pipe(b(!1))).pipe(l()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(u((t=>({id:'NoProviders',category:a.VIDEO_PIPELINE,message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(S(),u((()=>y()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(S(),u((()=>y()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(S(),u((()=>y()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const r=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>r.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>r.next(!0))));const o=new t(!0);this.subscription.add(e.current$.subscribe((()=>o.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(v((({to:t})=>t===P.PLAYING)),S()).subscribe((()=>o.next(!1))));let h=0;const c=d(e.providerOutput.isBuffering$,r,o).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=r.getValue()||o.getValue();return t&&!i})),l());this.subscription.add(c.subscribe((t=>{t?h=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(h),this.info.isStalled$.next(!1))})));const m=new i;this.subscription.add(m);const f=d(n(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(v((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(l()).subscribe((e=>{switch(p(this.providerContainer),m.unsubscribe(),e){case!0:{const e=new t(void 0);m.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),m.add(Ni({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:f,looped$:this.events.looped$,position$:e}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:m.add(Ni({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:f,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(u((t=>t?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(l(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(v((t=>t.length>0)),S()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=_t(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(d(this.desiredState.videoTrack.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(u((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const t=this.providerContainer?.providerOutput;p(this.providerContainer),p(t),$t={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{wt=t})),this.providerContainer.current$.subscribe((({type:t})=>At('provider',t))),t.duration$.subscribe((t=>At('duration',t))),t.availableVideoTracks$.pipe(v((t=>!!t.length)),S()).subscribe((t=>At('tracks',t))),this.events.fatalError$.subscribe(new Pt('fatalError')),this.events.managedError$.subscribe(new Pt('managedError')),t.position$.subscribe(new Pt('position')),t.currentVideoTrack$.pipe(u((t=>t?.quality))).subscribe(new Pt('quality')),this.info.currentBuffer$.subscribe(new Pt('buffer')),t.isBuffering$.subscribe(new Pt('isBuffering'))].forEach((t=>this.subscription.add(t))),At('codecs',Object.keys(ui).filter((t=>ui[t])))}}const Mi='@vkontakte/videoplayer-core@2.0.76';export{_ as ChromecastState,I as HttpConnectionType,P as PlaybackState,Oi as Player,Mi as SDK_VERSION,R as VideoFormat,B as VideoQuality};