@vkontakte/videoplayer-core 2.0.75-beta.0 → 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/es2015.cjs.d.ts +2 -2
- package/es2015.cjs.js +4 -4
- package/es2015.esm.d.ts +2 -2
- package/es2015.esm.js +4 -4
- package/es2018.cjs.d.ts +2 -2
- package/es2018.cjs.js +4 -4
- package/es2018.esm.d.ts +2 -2
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.d.ts +2 -2
- package/esnext.esm.js +4 -4
- package/index.d.ts +2 -2
- package/package.json +2 -2
- package/packages/core/src/providers/DashVKProvider/lib/types.d.ts +92 -0
- package/player/Player.d.ts +2 -3
- package/player/types.d.ts +3 -12
- package/providers/ProviderContainer/index.d.ts +3 -0
package/es2018.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.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
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2018.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce.js'));var a,r,n,o,u,l,d;exports.PlaybackState=void 0,(a=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',a.PLAYING='playing',a.PAUSED='paused',exports.VideoFormat=void 0,(r=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',r.DASH='DASH',r.DASH_SEP='DASH_SEP',r.DASH_SEP_VK='DASH_SEP',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_ONDEMAND_VK='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS',r.HLS_LIVE='HLS_LIVE',r.WEB_RTC_LIVE='WEB_RTC_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(n||(n={})),exports.ChromecastState=void 0,(o=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',o.AVAILABLE='AVAILABLE',o.CONNECTING='CONNECTING',o.CONNECTED='CONNECTED',exports.StartStatus=void 0,(u=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',u.SuccessWithoutSound='success_without_sound',u.Failed='failed',exports.HttpConnectionType=void 0,(l=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',l.HTTP2='http2',l.QUIC='quic',function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(d||(d={}));class h{constructor(e){var i;this.connection$=new t.ValueSubject(void 0),this.castState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new t.Subject,this.realCastState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const s='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const a=t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast),r=Boolean(window.__onGCastApiAvailable);var n;a?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',message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,a;null===(a=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===a||a.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,a;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(a=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===a?void 0:a.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 t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(c),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var r;const n=a===exports.ChromecastState.CONNECTED,o=t.isNonNullable(this.connection$.getValue());if(n&&!o){const a=s.getCurrentSession();t.assertNonNullable(a);const n=a.getCastDevice(),o=null===(r=a.getMediaSession())||void 0===r?void 0:r.media.contentId;(t.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:a,castDevice:n}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const c=e=>{switch(e){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return t.assertNever(e)}};var p;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(p||(p={}));var m,f=(e,i=0,s=p.OFFSET_P)=>{switch(s){case p.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case p.PLAYBACK_SHIFT:{if(0===i)return e;const t=new URL(e);return t.searchParams.append('playback_shift',i.toFixed(0)),t.toString()}default:t.assertNever(s)}return e},S=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};exports.VideoQuality=void 0,(m=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',m.Q_144P='144p',m.Q_240P='240p',m.Q_360P='360p',m.Q_480P='480p',m.Q_720P='720p',m.Q_1080P='1080p',m.Q_1440P='1440p',m.Q_2160P='2160p',m.Q_4320P='4320p';const b={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},v=(t,e)=>b[t].height>b[e].height,g=(t,e)=>b[t].height<b[e].height,y=Object.keys(b).sort(((t,e)=>g(t,e)?-1:1)),T=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return y.find((t=>{const e=b[t];return e.width>=s&&e.height>=i}))},E=t=>t===exports.VideoQuality.INVARIANT;class k{constructor(e){this.transitionStarted$=new t.Subject,this.transitionEnded$=new t.Subject,this.transitionUpdated$=new t.Subject,this.forceChanged$=new t.Subject,this.stateChangeStarted$=t.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=t.merge(this.transitionEnded$,this.forceChanged$),this.state=e}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(e){const i=this.transition,s=this.state;s===e||t.isNonNullable(i)&&i.to===e||(this.state=e,i?(this.transition={from:i.from,to:e,canceledTransition:i},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var w;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(w||(w={}));class P{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new k(w.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)if((null==a?void 0:a.to)===exports.PlaybackState.PAUSED||r.state!==d.Requested||e===w.STOPPED)switch(s){case exports.PlaybackState.PLAYING:switch(e){case w.PLAYING:break;case w.PAUSED:case w.READY:this.videoState.startTransitionTo(w.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case w.PLAYING:this.videoState.startTransitionTo(w.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case w.PAUSED:break;case w.READY:this.videoState.startTransitionTo(w.PAUSED),this.videoState.setState(w.PAUSED);break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}else this.seek(r.position)}else e!==w.STOPPED&&(this.videoState.startTransitionTo(w.STOPPED),this.stop())},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next((e=>{switch(e){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(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 t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(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===d.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,a=this.params.output.isBuffering$.getValue(),r=s===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:t.assertNever(s)}})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));i(t.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(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(w.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(w.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.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:d.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==w.PAUSED&&t!==w.PLAYING||(this.videoState.setState(w.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==w.PLAYING&&t!==w.PAUSED||(this.videoState.setState(w.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===w.READY&&this.videoState.setState(w.READY)}handleRemoteStop(){this.videoState.getState()!==w.STOPPED&&this.videoState.setState(w.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),a={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};a.volume===s.volume&&a.muted==a.muted||this.params.output.volume$.next(a)}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(e){var i;const s=this.params.source;let a,r,n;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const o=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:g(t,e)?1:-1))[0];t.assertNonNullable(o);const u=i[o];t.assertNonNullable(u),a=u,r='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),a=f(i.url),r='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.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 exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}const o=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:a,r);o.contentUrl=a,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:l}=this.params.meta;return t.isNonNullable(u)&&(o.metadata.title=u),t.isNonNullable(l)&&(o.metadata.subtitle=l),o}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===d.Applying||i.state===d.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(e){const i=this.params.connection.session.loadMedia(e),s=new Promise(((e,i)=>{this.loadMediaTimeoutSubscription.add(t.timeout(7e3).subscribe((()=>i('timeout(7000)'))))}));Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===d.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:e,thrown:t})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}class ${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 A extends ${constructor(){super(),this.listeners||$.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class x{constructor(){Object.defineProperty(this,'signal',{value:new A,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 N(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(x.prototype[Symbol.toStringTag]='AbortController',A.prototype[Symbol.toStringTag]='AbortSignal');const R=N({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),D=R?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(!N({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,_=R?D.fetch:window.fetch;R?D.Request:window.Request;const C=R?x:window.AbortController,I=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class L{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=I(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){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),a=this.activeRequests.get(i.url);s&&a&&a.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(I),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 C,u=o.signal,l={url:t,from:s,to:a,loaded:0,data:null,abortController:o};u.addEventListener('abort',(()=>this.onBigRequestAbort(l)));const d=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return _(n,{signal:u}).then((t=>{var e,i,r;if(l.response=t,!t.ok||!t.body)return void this.onBigRequestError(l);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const u=n.getReader(),h=parseInt(null!==(r=t.headers.get('Content-Length'))&&void 0!==r?r:'',10)||a-s+1;l.data=new ArrayBuffer(h);const c=new Uint8Array(l.data),p=async({done:t,value:e})=>{t?this.onBigRequestProgress(l):e&&(c.set(e,l.loaded),l.loaded+=e.byteLength,this.onBigRequestProgress(l),await(null==u?void 0:u.read().then(p,L.suppressStreamErrors).catch(d)))};null==u||u.read().then(p,L.suppressStreamErrors).catch(d)}),L.suppressAbort).catch((t=>this.onBigRequestError(l,t))),l}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a,response:r}){var n,o,u,l,d,h,c,p;if(!this.activeRequests.has(t)||!a)return;const m=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const n of m){const{request:m}=n,[f,S]=I(m),b=f>=e&&S<=e+s,v=e>=f&&e+s<S,g=a.slice(f-e,Math.min(S-e+1,s));if((b||v)&&(m.requestStartDate=null!==(o=m.requestStartDate)&&void 0!==o?o:new Date,m.firstByteDate=null!==(u=m.firstByteDate)&&void 0!==u?u:new Date,m.bytesLoaded=g.byteLength,m.bytesTotal=i-e),b){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(l=this.dashJsRequestQueue.get(t))&&void 0!==l?l:[]).filter((t=>t!==n))),null===(d=n.success)||void 0===d||d.call(n,g,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(h=this.dashMetrics)||void 0===h||h.addHttpRequest(m,t,null!==(c=null==r?void 0:r.status)&&void 0!==c?c:200,e,[])}else v&&(null===(p=n.progress)||void 0===p||p.call(n,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var a,r,n,o;if(null===(r=(a=this.params).onError)||void 0===r||r.call(a,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const u=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of u){const[a,r]=I(t.request);(a>=e&&a<i||r>e&&r<=i)&&(null===(o=null==t?void 0:t.error)||void 0===o||o.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,a;if(!this.activeRequests.has(t))return;const r=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of r){const[s,r]=I(t.request);(s>=e&&s<i||r>e&&r<=i)&&(null===(a=null==t?void 0:t.abort)||void 0===a||a.call(t,t.request))}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class O{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(O.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;O.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const B=(t,e)=>{const i=new L(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 O(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var M=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&(null==e||e())}}}),!0)},V='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},U=function(t){try{return!!t()}catch(t){return!0}},F=!U((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),q=F,j=Function.prototype,H=j.bind,G=j.call,Y=q&&H.bind(G,G),Q=q?function(t){return t&&Y(t)}:function(t){return t&&function(){return G.apply(t,arguments)}},z=Q,W=z({}.toString),J=z(''.slice),X=function(t){return J(W(t),8,-1)},K=U,Z=X,tt=Object,et=Q(''.split),it=K((function(){return!tt('z').propertyIsEnumerable(0)}))?function(t){return'String'==Z(t)?et(t,''):tt(t)}:tt,st=TypeError,at=function(t){if(null==t)throw st('Can\'t call method on '+t);return t},rt=it,nt=at,ot=function(t){return rt(nt(t))},ut={},lt=function(t){return t&&t.Math==Math&&t},dt=lt('object'==typeof globalThis&&globalThis)||lt('object'==typeof window&&window)||lt('object'==typeof self&&self)||lt('object'==typeof V&&V)||function(){return this}()||Function('return this')(),ht=function(t){return'function'==typeof t},ct=dt,pt=Object.defineProperty,mt=function(t,e){try{pt(ct,t,{value:e,configurable:!0,writable:!0})}catch(i){ct[t]=e}return e},ft=dt['__core-js_shared__']||mt('__core-js_shared__',{}),St=ht,bt=ft,vt=Q(Function.toString);St(bt.inspectSource)||(bt.inspectSource=function(t){return vt(t)});var gt,yt,Tt=ht,Et=bt.inspectSource,kt=dt.WeakMap,wt=Tt(kt)&&/native code/.test(Et(kt)),Pt=ht,$t=function(t){return'object'==typeof t?null!==t:Pt(t)},At=!U((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),xt={},Nt=$t,Rt=dt.document,Dt=Nt(Rt)&&Nt(Rt.createElement),_t=function(t){return Dt?Rt.createElement(t):{}},Ct=_t,It=!At&&!U((function(){return 7!=Object.defineProperty(Ct('div'),'a',{get:function(){return 7}}).a})),Lt=At&&U((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),Ot=$t,Bt=String,Mt=TypeError,Vt=function(t){if(Ot(t))return t;throw Mt(Bt(t)+' is not an object')},Ut=F,Ft=Function.prototype.call,qt=Ut?Ft.bind(Ft):function(){return Ft.apply(Ft,arguments)},jt={},Ht=jt,Gt=dt,Yt=ht,Qt=function(t){return Yt(t)?t:void 0},zt=function(t,e){return arguments.length<2?Qt(Ht[t])||Qt(Gt[t]):Ht[t]&&Ht[t][e]||Gt[t]&&Gt[t][e]},Wt=Q({}.isPrototypeOf),Jt=dt,Xt=zt('navigator','userAgent')||'',Kt=Jt.process,Zt=Jt.Deno,te=Kt&&Kt.versions||Zt&&Zt.version,ee=te&&te.v8;ee&&(yt=(gt=ee.split('.'))[0]>0&>[0]<4?1:+(gt[0]+gt[1])),!yt&&Xt&&(!(gt=Xt.match(/Edge\/(\d+)/))||gt[1]>=74)&&(gt=Xt.match(/Chrome\/(\d+)/))&&(yt=+gt[1]);var ie=yt,se=U,ae=!!Object.getOwnPropertySymbols&&!se((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&ie&&ie<41})),re=ae&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,ne=zt,oe=ht,ue=Wt,le=Object,de=re?function(t){return'symbol'==typeof t}:function(t){var e=ne('Symbol');return oe(e)&&ue(e.prototype,le(t))},he=String,ce=function(t){try{return he(t)}catch(t){return'Object'}},pe=ht,me=ce,fe=TypeError,Se=function(t){if(pe(t))return t;throw fe(me(t)+' is not a function')},be=Se,ve=function(t,e){var i=t[e];return null==i?void 0:be(i)},ge=qt,ye=ht,Te=$t,Ee=TypeError,ke={exports:{}},we=ft;(ke.exports=function(t,e){return we[t]||(we[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.24.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.24.1/LICENSE',source:'https://github.com/zloirock/core-js'});var Pe=at,$e=Object,Ae=function(t){return $e(Pe(t))},xe=Ae,Ne=Q({}.hasOwnProperty),Re=Object.hasOwn||function(t,e){return Ne(xe(t),e)},De=Q,_e=0,Ce=Math.random(),Ie=De(1..toString),Le=function(t){return'Symbol('+(void 0===t?'':t)+')_'+Ie(++_e+Ce,36)},Oe=dt,Be=ke.exports,Me=Re,Ve=Le,Ue=ae,Fe=re,qe=Be('wks'),je=Oe.Symbol,He=je&&je.for,Ge=Fe?je:je&&je.withoutSetter||Ve,Ye=function(t){if(!Me(qe,t)||!Ue&&'string'!=typeof qe[t]){var e='Symbol.'+t;Ue&&Me(je,t)?qe[t]=je[t]:qe[t]=Fe&&He?He(e):Ge(e)}return qe[t]},Qe=qt,ze=$t,We=de,Je=ve,Xe=function(t,e){var i,s;if('string'===e&&ye(i=t.toString)&&!Te(s=ge(i,t)))return s;if(ye(i=t.valueOf)&&!Te(s=ge(i,t)))return s;if('string'!==e&&ye(i=t.toString)&&!Te(s=ge(i,t)))return s;throw Ee('Can\'t convert object to primitive value')},Ke=TypeError,Ze=Ye('toPrimitive'),ti=function(t,e){if(!ze(t)||We(t))return t;var i,s=Je(t,Ze);if(s){if(void 0===e&&(e='default'),i=Qe(s,t,e),!ze(i)||We(i))return i;throw Ke('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),Xe(t,e)},ei=de,ii=function(t){var e=ti(t,'string');return ei(e)?e:e+''},si=At,ai=It,ri=Lt,ni=Vt,oi=ii,ui=TypeError,li=Object.defineProperty,di=Object.getOwnPropertyDescriptor;xt.f=si?ri?function(t,e,i){if(ni(t),e=oi(e),ni(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=di(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return li(t,e,i)}:li:function(t,e,i){if(ni(t),e=oi(e),ni(i),ai)try{return li(t,e,i)}catch(t){}if('get'in i||'set'in i)throw ui('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var hi,ci,pi,mi=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},fi=xt,Si=mi,bi=At?function(t,e,i){return fi.f(t,e,Si(1,i))}:function(t,e,i){return t[e]=i,t},vi=ke.exports,gi=Le,yi=vi('keys'),Ti=function(t){return yi[t]||(yi[t]=gi(t))},Ei={},ki=wt,wi=dt,Pi=Q,$i=$t,Ai=bi,xi=Re,Ni=ft,Ri=Ti,Di=Ei,_i=wi.TypeError,Ci=wi.WeakMap;if(ki||Ni.state){var Ii=Ni.state||(Ni.state=new Ci),Li=Pi(Ii.get),Oi=Pi(Ii.has),Bi=Pi(Ii.set);hi=function(t,e){if(Oi(Ii,t))throw new _i('Object already initialized');return e.facade=t,Bi(Ii,t,e),e},ci=function(t){return Li(Ii,t)||{}},pi=function(t){return Oi(Ii,t)}}else{var Mi=Ri('state');Di[Mi]=!0,hi=function(t,e){if(xi(t,Mi))throw new _i('Object already initialized');return e.facade=t,Ai(t,Mi,e),e},ci=function(t){return xi(t,Mi)?t[Mi]:{}},pi=function(t){return xi(t,Mi)}}var Vi={set:hi,get:ci,has:pi,enforce:function(t){return pi(t)?ci(t):hi(t,{})},getterFor:function(t){return function(e){var i;if(!$i(e)||(i=ci(e)).type!==t)throw _i('Incompatible receiver, '+t+' required');return i}}},Ui=F,Fi=Function.prototype,qi=Fi.apply,ji=Fi.call,Hi='object'==typeof Reflect&&Reflect.apply||(Ui?ji.bind(qi):function(){return ji.apply(qi,arguments)}),Gi={},Yi={},Qi={}.propertyIsEnumerable,zi=Object.getOwnPropertyDescriptor,Wi=zi&&!Qi.call({1:2},1);Yi.f=Wi?function(t){var e=zi(this,t);return!!e&&e.enumerable}:Qi;var Ji=At,Xi=qt,Ki=Yi,Zi=mi,ts=ot,es=ii,is=Re,ss=It,as=Object.getOwnPropertyDescriptor;Gi.f=Ji?as:function(t,e){if(t=ts(t),e=es(e),ss)try{return as(t,e)}catch(t){}if(is(t,e))return Zi(!Xi(Ki.f,t,e),t[e])};var rs=U,ns=ht,os=/#|\.prototype\./,us=function(t,e){var i=ds[ls(t)];return i==cs||i!=hs&&(ns(e)?rs(e):!!e)},ls=us.normalize=function(t){return String(t).replace(os,'.').toLowerCase()},ds=us.data={},hs=us.NATIVE='N',cs=us.POLYFILL='P',ps=us,ms=Se,fs=F,Ss=Q(Q.bind),bs=function(t,e){return ms(t),void 0===e?t:fs?Ss(t,e):function(){return t.apply(e,arguments)}},vs=dt,gs=Hi,ys=Q,Ts=ht,Es=Gi.f,ks=ps,ws=jt,Ps=bs,$s=bi,As=Re,xs=function(t){var e=function(i,s,a){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,a)}return gs(t,this,arguments)};return e.prototype=t.prototype,e},Ns=function(t,e){var i,s,a,r,n,o,u,l,d=t.target,h=t.global,c=t.stat,p=t.proto,m=h?vs:c?vs[d]:(vs[d]||{}).prototype,f=h?ws:ws[d]||$s(ws,d,{})[d],S=f.prototype;for(a in e)i=!ks(h?a:d+(c?'.':'#')+a,t.forced)&&m&&As(m,a),n=f[a],i&&(o=t.dontCallGetSet?(l=Es(m,a))&&l.value:m[a]),r=i&&o?o:e[a],i&&typeof n==typeof r||(u=t.bind&&i?Ps(r,vs):t.wrap&&i?xs(r):p&&Ts(r)?ys(r):r,(t.sham||r&&r.sham||n&&n.sham)&&$s(u,'sham',!0),$s(f,a,u),p&&(As(ws,s=d+'Prototype')||$s(ws,s,{}),$s(ws[s],a,r),t.real&&S&&!S[a]&&$s(S,a,r)))},Rs=At,Ds=Re,_s=Function.prototype,Cs=Rs&&Object.getOwnPropertyDescriptor,Is=Ds(_s,'name'),Ls={EXISTS:Is,PROPER:Is&&'something'===function(){}.name,CONFIGURABLE:Is&&(!Rs||Rs&&Cs(_s,'name').configurable)},Os={},Bs=Math.ceil,Ms=Math.floor,Vs=Math.trunc||function(t){var e=+t;return(e>0?Ms:Bs)(e)},Us=function(t){var e=+t;return e!=e||0===e?0:Vs(e)},Fs=Us,qs=Math.max,js=Math.min,Hs=Us,Gs=Math.min,Ys=function(t){return t>0?Gs(Hs(t),9007199254740991):0},Qs=function(t){return Ys(t.length)},zs=ot,Ws=function(t,e){var i=Fs(t);return i<0?qs(i+e,0):js(i,e)},Js=Qs,Xs=function(t){return function(e,i,s){var a,r=zs(e),n=Js(r),o=Ws(s,n);if(t&&i!=i){for(;n>o;)if((a=r[o++])!=a)return!0}else for(;n>o;o++)if((t||o in r)&&r[o]===i)return t||o||0;return!t&&-1}},Ks={includes:Xs(!0),indexOf:Xs(!1)},Zs=Re,ta=ot,ea=Ks.indexOf,ia=Ei,sa=Q([].push),aa=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],ra=function(t,e){var i,s=ta(t),a=0,r=[];for(i in s)!Zs(ia,i)&&Zs(s,i)&&sa(r,i);for(;e.length>a;)Zs(s,i=e[a++])&&(~ea(r,i)||sa(r,i));return r},na=aa,oa=Object.keys||function(t){return ra(t,na)},ua=At,la=Lt,da=xt,ha=Vt,ca=ot,pa=oa;Os.f=ua&&!la?Object.defineProperties:function(t,e){ha(t);for(var i,s=ca(e),a=pa(e),r=a.length,n=0;r>n;)da.f(t,i=a[n++],s[i]);return t};var ma,fa=zt('document','documentElement'),Sa=Vt,ba=Os,va=aa,ga=Ei,ya=fa,Ta=_t,Ea=Ti('IE_PROTO'),ka=function(){},wa=function(t){return'<script>'+t+'<\/script>'},Pa=function(t){t.write(wa('')),t.close();var e=t.parentWindow.Object;return t=null,e},$a=function(){try{ma=new ActiveXObject('htmlfile')}catch(t){}var t,e;$a='undefined'!=typeof document?document.domain&&ma?Pa(ma):((e=Ta('iframe')).style.display='none',ya.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(wa('document.F=Object')),t.close(),t.F):Pa(ma);for(var i=va.length;i--;)delete $a.prototype[va[i]];return $a()};ga[Ea]=!0;var Aa,xa,Na,Ra=Object.create||function(t,e){var i;return null!==t?(ka.prototype=Sa(t),i=new ka,ka.prototype=null,i[Ea]=t):i=$a(),void 0===e?i:ba.f(i,e)},Da=!U((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),_a=Re,Ca=ht,Ia=Ae,La=Da,Oa=Ti('IE_PROTO'),Ba=Object,Ma=Ba.prototype,Va=La?Ba.getPrototypeOf:function(t){var e=Ia(t);if(_a(e,Oa))return e[Oa];var i=e.constructor;return Ca(i)&&e instanceof i?i.prototype:e instanceof Ba?Ma:null},Ua=bi,Fa=function(t,e,i,s){return s&&s.enumerable?t[e]=i:Ua(t,e,i),t},qa=U,ja=ht,Ha=Ra,Ga=Va,Ya=Fa,Qa=Ye('iterator'),za=!1;[].keys&&('next'in(Na=[].keys())?(xa=Ga(Ga(Na)))!==Object.prototype&&(Aa=xa):za=!0);var Wa=null==Aa||qa((function(){var t={};return Aa[Qa].call(t)!==t}));ja((Aa=Wa?{}:Ha(Aa))[Qa])||Ya(Aa,Qa,(function(){return this}));var Ja={IteratorPrototype:Aa,BUGGY_SAFARI_ITERATORS:za},Xa={};Xa[Ye('toStringTag')]='z';var Ka='[object z]'===String(Xa),Za=Ka,tr=ht,er=X,ir=Ye('toStringTag'),sr=Object,ar='Arguments'==er(function(){return arguments}()),rr=Za?er:function(t){var e,i,s;return void 0===t?'Undefined':null===t?'Null':'string'==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=sr(t),ir))?i:ar?er(e):'Object'==(s=er(e))&&tr(e.callee)?'Arguments':s},nr=rr,or=Ka?{}.toString:function(){return'[object '+nr(this)+']'},ur=Ka,lr=xt.f,dr=bi,hr=Re,cr=or,pr=Ye('toStringTag'),mr=function(t,e,i,s){if(t){var a=i?t:t.prototype;hr(a,pr)||lr(a,pr,{configurable:!0,value:e}),s&&!ur&&dr(a,'toString',cr)}},fr=Ja.IteratorPrototype,Sr=Ra,br=mi,vr=mr,gr=ut,yr=function(){return this},Tr=(TypeError,Q);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Tr(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Er=Ns,kr=qt,wr=function(t,e,i,s){var a=e+' Iterator';return t.prototype=Sr(fr,{next:br(+!s,i)}),vr(t,a,!1,!0),gr[a]=yr,t},Pr=Va,$r=mr,Ar=Fa,xr=ut,Nr=Ls.PROPER,Rr=Ja.BUGGY_SAFARI_ITERATORS,Dr=Ye('iterator'),_r=function(){return this},Cr=ot,Ir=ut,Lr=Vi;xt.f;var Or=function(t,e,i,s,a,r,n){wr(i,e,s);var o,u,l,d=function(t){if(t===a&&f)return f;if(!Rr&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},h=e+' Iterator',c=!1,p=t.prototype,m=p[Dr]||p['@@iterator']||a&&p[a],f=!Rr&&m||d(a),S='Array'==e&&p.entries||m;if(S&&(o=Pr(S.call(new t)))!==Object.prototype&&o.next&&($r(o,h,!0,!0),xr[h]=_r),Nr&&'values'==a&&m&&'values'!==m.name&&(c=!0,f=function(){return kr(m,this)}),a)if(u={values:d('values'),keys:r?f:d('keys'),entries:d('entries')},n)for(l in u)(Rr||c||!(l in p))&&Ar(p,l,u[l]);else Er({target:e,proto:!0,forced:Rr||c},u);return n&&p[Dr]!==f&&Ar(p,Dr,f,{name:a}),xr[e]=f,u},Br=Lr.set,Mr=Lr.getterFor('Array Iterator');Or(Array,'Array',(function(t,e){Br(this,{type:'Array Iterator',target:Cr(t),index:0,kind:e})}),(function(){var t=Mr(this),e=t.target,i=t.kind,s=t.index++;return!e||s>=e.length?(t.target=void 0,{value:void 0,done:!0}):'keys'==i?{value:s,done:!1}:'values'==i?{value:e[s],done:!1}:{value:[s,e[s]],done:!1}}),'values'),Ir.Arguments=Ir.Array;var Vr=ut,Ur=Ye('iterator'),Fr=Array.prototype,qr=rr,jr=ve,Hr=ut,Gr=Ye('iterator'),Yr=function(t){if(null!=t)return jr(t,Gr)||jr(t,'@@iterator')||Hr[qr(t)]},Qr=qt,zr=Se,Wr=Vt,Jr=ce,Xr=Yr,Kr=TypeError,Zr=qt,tn=Vt,en=ve,sn=bs,an=qt,rn=Vt,nn=ce,on=function(t){return void 0!==t&&(Vr.Array===t||Fr[Ur]===t)},un=Qs,ln=Wt,dn=function(t,e){var i=arguments.length<2?Xr(t):e;if(zr(i))return Wr(Qr(i,t));throw Kr(Jr(t)+' is not iterable')},hn=Yr,cn=function(t,e,i){var s,a;tn(t);try{if(!(s=en(t,'return'))){if('throw'===e)throw i;return i}s=Zr(s,t)}catch(t){a=!0,s=t}if('throw'===e)throw i;if(a)throw s;return tn(s),i},pn=TypeError,mn=function(t,e){this.stopped=t,this.result=e},fn=mn.prototype,Sn=ii,bn=xt,vn=mi,gn=function(t,e,i){var s,a,r,n,o,u,l,d=i&&i.that,h=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=sn(e,d),S=function(t){return s&&cn(s,'normal',t),new mn(!0,t)},b=function(t){return h?(rn(t),m?f(t[0],t[1],S):f(t[0],t[1])):m?f(t,S):f(t)};if(c)s=t.iterator;else if(p)s=t;else{if(!(a=hn(t)))throw pn(nn(t)+' is not iterable');if(on(a)){for(r=0,n=un(t);n>r;r++)if((o=b(t[r]))&&ln(fn,o))return o;return new mn(!1)}s=dn(t,a)}for(u=c?t.next:s.next;!(l=an(u,s)).done;){try{o=b(l.value)}catch(t){cn(s,'throw',t)}if('object'==typeof o&&o&&ln(fn,o))return o}return new mn(!1)},yn=function(t,e,i){var s=Sn(e);s in t?bn.f(t,s,vn(0,i)):t[s]=i};Ns({target:'Object',stat:!0},{fromEntries:function(t){var e={};return gn(t,(function(t,i){yn(e,t,i)}),{AS_ENTRIES:!0}),e}});var Tn=jt.Object.fromEntries,En={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},kn=dt,wn=rr,Pn=bi,$n=ut,An=Ye('toStringTag');for(var xn in En){var Nn=kn[xn],Rn=Nn&&Nn.prototype;Rn&&wn(Rn)!==An&&Pn(Rn,An,xn),$n[xn]=$n.Array}var Dn=Tn,_n=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject,a=new t.ValueSubject(void 0),r=new t.ValueSubject(void 0);let n=NaN,o=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,u=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const u=e.onload,l=e.progress;e.onload=function(...e){return(e=>{var s,n,o,u,l;const d=Dn(e.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in d||'x-playback-duration-millis'in d){const a=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),r=parseInt(null!==(n=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==n?n:'',10),u=null!==(o=null!=r?r:1e3*a)&&void 0!==o?o:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)}const h=null!==(u=d['x-delivery-type'])&&void 0!==u?u:exports.HttpConnectionType.HTTP1,c=null!==(l={1:!0,0:!1}[d['x-reused']])&&void 0!==l?l:void 0;a.next(h),r.next(c)})(this),u(...e)},e.progress=function(...t){return this.readyState>=2&&!o&&(o=!0,s.next(Date.now()-n)),l(...t)},n=Date.now(),o=!1}return u(e)}}}),!0),{playbackDuration$:i,ping$:s,connectionReused$:r,connectionType$:a}},Cn=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},In=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 Ln=(e,i,s,{equal:a=((t,e)=>t===e),changed$:r,onError:n}={})=>{const o=e.getState(),u=i(),l=t.isNullable(r),d=new t.Subscription;return r&&d.add(r.subscribe((t=>{const i=e.getState();a(t,i)&&e.setState(t)}),n)),a(u,o)||(s(o),l&&e.setState(o)),d.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),l&&e.setState(t.to)}),n)),d},On=(e,i,s)=>Ln(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),Bn=(e,i,s,a)=>Ln(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:s,onError:a}),Mn=(e,i,s,a)=>Ln(i,(()=>e.playbackRate),(i=>{t.isNonNullable(i)&&(e.playbackRate=i)}),{changed$:s,onError:a}),Vn=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class Un{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const a=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Ln(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(Ln(i.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(Ln(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);const a=t=>{var e,i,s,r,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(r=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==r?r:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',a))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',a)}))),this.subscription.add(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter(Un.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(e){t.assertNonNullable(this.video);for(const i of this.htmlTextTracksAsArray(!0))t.isNonNullable(e)&&Vn(i,e)?i.mode='showing':i.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(e){t.assertNonNullable(this.video);const i=document.createElement('track');i.setAttribute('src',e.url),i.setAttribute('id',e.id),e.label&&i.setAttribute('label',e.label),e.language&&i.setAttribute('srclang',e.language),this.externalTracks.set(e.id,e),this.video.appendChild(i)}detach(e){t.assertNonNullable(this.video);const i=Array.prototype.find.call(this.video.getElementsByTagName('track'),(t=>t.getAttribute('id')===e));i&&this.video.removeChild(i),this.externalTracks.delete(e)}}var Fn=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class qn{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}class jn{constructor(t){this._buffer=[],this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to: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 Hn=(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 Gn=e=>{const i=i=>t.fromEvent(e,i).pipe(t.mapTo(void 0));['canplaythrough','playing','pause','canplay','seeked','seeking','loadstart','loadedmetadata','loadeddata','durationchange'].map((t=>e.addEventListener(t,(e=>{console.log('HTMLVideoElement',t,e)}))));const s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((t=>'ended'===t.type?e.readyState<2:e.readyState<3)),t.filterChanged()),a=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>Hn(e.buffered,e.currentTime)))),r=t.fromEvent(e,'volumechange').pipe(t.debounce(0),t.map((()=>({muted:e.muted,volume:e.volume})))),n=t.fromEvent(e,'ratechange').pipe(t.map((()=>e.playbackRate))),o=t.fromEvent(e,'error').pipe(t.filter((t=>{const i=Boolean(e.error);return console.log('HTMLVideoElement error','ignoring:',!i,{errorField:e.error,readyState:e.readyState,event:t,src:e.src}),console.trace(),i})),t.map((()=>{var t;const i=e.error;return{id:i?`MediaError#${i.code}`:'HtmlVideoError',message:i?i.message:'Error event from HTML video element',thrown:null!==(t=e.error)&&void 0!==t?t:void 0}}))),u=t.fromEvent(e,'timeupdate').pipe(t.map((()=>e.currentTime))),l=new t.Subject;let d;return u.subscribe((i=>{e.loop&&t.isNonNullable(d)&&t.isNonNullable(i)&&d>=e.duration-.3&&i<=.3&&l.next(d),d=i})),{playing$:i('playing'),pause$:i('pause').pipe(t.filter((()=>!e.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:l,error$:o,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:u,durationChange$:t.fromEvent(e,'durationchange').pipe(t.map((()=>e.duration))),isBuffering$:s,currentBuffer$:a,volumeState$:r,playbackRateState$:n}},Yn=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var Qn=Ae,zn=Qs,Wn=Us;Ns({target:'Array',proto:!0},{at:function(t){var e=Qn(this),i=zn(e),s=Wn(t),a=s>=0?s:i+s;return a<0||a>=i?void 0:e[a]}});var Jn=zt('Array','at');let Xn=!1,Kn={};const Zn=t=>{t(Kn)},to=(t,e)=>{var i;Xn&&(Kn.meta=null!==(i=Kn.meta)&&void 0!==i?i:{},Kn.meta[t]=e)};class eo{constructor(t){this.name=t}next(t){var e,i;if(!Xn)return;Kn.series=null!==(e=Kn.series)&&void 0!==e?e:{};const s=null!==(i=Kn.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Kn.series[this.name]=s}}const io=new eo('best_bitrate');class so{constructor(){this.history={}}recordSelection(e){this.history[e.id]=t.now()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const ao=(e,{container:i,throughput:s,tuning:a,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:l,history:d})=>{var h,c,p,m;const f=a.usePixelRatio&&null!==(h=window.devicePixelRatio)&&void 0!==h?h:1,S=a.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*f*a.containerSizeFactor,height:i.height*f*a.containerSizeFactor},y=S&&T(S),k=a.considerPlaybackRate&&t.isNonNullable(u)?u:1,w=e.filter((t=>!E(t.quality))).sort(((t,e)=>v(t.quality,e.quality)?-1:1)),P=null===(c=Jn(w,-1))||void 0===c?void 0:c.quality,$=null===(p=Jn(w,0))||void 0===p?void 0:p.quality,A=t.isNullable(r)||t.isNonNullable(r.min)&&t.isNonNullable(r.max)&&g(r.max,r.min)||t.isNonNullable(r.min)&&$&&v(r.min,$)||t.isNonNullable(r.max)&&P&&g(r.max,P),x=k*(N=null!=o?o:.5,R=a.bitrateFactorAtEmptyBuffer,D=a.bitrateFactorAtFullBuffer,(R-D)*Math.pow(2,-10*N)+D);var N,R,D;const _=w.filter((e=>{const i=!y||g(e.quality,y),u=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s-n>=e.bitrate*x,d=a.lazyQualitySwitch&&t.isNonNullable(a.minBufferToSwitchUp)&&l&&!E(l.quality)&&(null!=o?o:0)<a.minBufferToSwitchUp&&v(e.quality,l.quality),h=A||(t.isNullable(r.max)||(c=e.quality,p=r.max,b[c].height<=b[p].height))&&(t.isNullable(r.min)||((t,e)=>b[t].height>=b[e].height)(e.quality,r.min));var c,p;return i&&u&&!d&&h}))[0];_&&_.bitrate&&io.next(_.bitrate);const C=null!==(m=null!=_?_:w[Math.ceil((w.length-1)/2)])&&void 0!==m?m:e[0],I=C&&d&&d.history[C.id]&&t.now()-d.history[C.id]<=a.trackCooldown&&(!d.last||C.id!==d.last.id);if((null==C?void 0:C.id)&&d&&!I&&d.recordSelection(C),I&&(null==d?void 0:d.last)){const t=d.last;return null==d||d.recordSwitch(t),t}return null==d||d.recordSwitch(C),C};var ro=t=>new URL(t).hostname;const no=(e,i=300)=>new t.Observable((a=>{const{width:r,height:n}=e.getBoundingClientRect();if(a.next({width:r,height:n}),!window.ResizeObserver)return;const o=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,r;i.contentBoxSize&&i.contentBoxSize[0]?(r=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,r=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(r)&&a.next({width:s,height:r})}),i));return o.observe(e),()=>o.disconnect()})),oo={};var uo;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(uo||(uo={}));const lo=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class ho{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(uo.DOWNLOADING_LIB),this.textTracksManager=new Un,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t.ValueSubject(void 0),this.maxSeekBackTime$=new t.ValueSubject(1/0),this.availableFrom$=new t.ValueSubject(void 0),this.elementSize$=new t.ValueSubject(void 0),this.liveOffset=new qn,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&e!==uo.DOWNLOADING_LIB&&e!==uo.STREAM_INITIALIZED)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===d.Requested&&e!==uo.STOPPED&&i!==exports.PlaybackState.STOPPED&&(r?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case exports.PlaybackState.STOPPED:switch(e){case uo.STOPPED:break;case uo.PLAYING:case uo.PAUSED:case uo.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case uo.PLAYING:break;case uo.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case uo.READY:this.play();break;case uo.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case uo.PLAYING:this.pause(),this.liveOffset.pause();break;case uo.PAUSED:break;case uo.READY:this.videoState.setState(uo.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case uo.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Fn(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ro(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((e=>{t||(oo.MediaPlayer=e.MediaPlayer,oo.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(oo.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(oo.Debug,'dashjs not loaded'),this.player=oo.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter((t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Yn(t.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=B(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&&In(this.player),M(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:Cn})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(uo.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:t})},a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(no(this.video),this.elementSize$),a(lo(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),a(lo(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const r=lo(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));r.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===uo.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(Ln(i.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(Ln(i.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:s})),a(lo(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),a(lo(this.player,'fragmentLoadingStarted'),(({mediaType:t,request:{url:i}})=>{var s,a;const r=this.player.getDashMetrics(),n=r.getLatestFragmentRequestHeaderValueByID(t,'X-Reused'),o=null!==(s=r.getLatestFragmentRequestHeaderValueByID(t,'X-Delivery-Type'))&&void 0!==s?s:exports.HttpConnectionType.HTTP1,u=null!==(a={1:!0,0:!1}[n])&&void 0!==a?a:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(u),e.hostname$.next(ro(i))})),a(lo(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),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=T(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===a&&(r=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&e.currentVideoTrack$.next(r),this.videoState.setState(uo.STREAM_INITIALIZED),this.videoState.startTransitionTo(uo.READY)})),a(lo(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),a(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=ao(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const n=lo(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));a(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:n}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(n.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),a(lo(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),a(lo(this.player,'playbackEnded'),e.endedEvent$),a(lo(this.player,'playbackProgress').pipe(t.map((()=>Hn(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),a(lo(this.player,'playbackPlaying'),(()=>{this.videoState.setState(uo.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)})),a(lo(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(uo.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(lo(this.player,'playbackPaused'),(()=>{this.videoState.setState(uo.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)})),a(lo(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===uo.READY&&this.videoState.setState(uo.READY)})),a(this.isLive$,e.isLive$),a(no(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:o,ping$:u,connectionType$:l,connectionReused$:d}=_n(this.player);a(l,this.params.output.httpConnectionType$),a(d,this.params.output.httpConnectionReused$),a(o,this.maxSeekBackTime$),a(u.pipe(t.once()),e.firstBytesEvent$),a(lo(this.player,'canPlay'),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(n.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(lo(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{this.subscription.add(lo(this.player,'playbackPlaying').pipe(t.once(),t.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))}),s)),this.subscription.add(On(this.video,i.isLooped,s));const{volumeState$:h,looped$:c,playbackRateState$:p}=Gn(this.video);this.subscription.add(Bn(this.video,i.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(c.subscribe(e.loopedEvent$)),this.subscription.add(Mn(this.video,i.playbackRate,p,s))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(uo.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(uo.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=f(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,p.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(uo.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(uo.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var co=t=>{switch(t){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}},po=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 mo(){return t.now()}function fo(t){return mo()-t}function So(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 bo(e,i,s,a){const r=window.XMLHttpRequest;let n,o,u,l,d,h=!1,c=0,p=!1,m='arraybuffer',f=7e3,S=2e3,b=()=>{if(h)return;t.assertNonNullable(l);const e=fo(l);let i;if(e<S)return i=S-e,void setTimeout(b,i);S*=2,S>f&&(S=f),o&&o.abort(),o=new r,g()};const v=()=>{if(!h){if(--c>=0)return b(),void(a&&a());h=!0,d&&d(),s&&s()}},g=()=>{l=mo(),o=new r,o.open('get',e);let s,a=0,c=0;const f=()=>(t.assertNonNullable(l),Math.max(l,Math.max(s||0,c||0)));if(n&&o.addEventListener('progress',(t=>{const e=mo();n.updateChunk&&t.loaded>a&&(n.updateChunk(f(),t.loaded-a),a=t.loaded,s=e)})),u&&(o.timeout=u,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(h)return;t.assertNonNullable(o);const e=o.status;if(e>=200&&e<300){if(o.response.byteLength&&n){const t=o.response.byteLength-a;t&&n.updateChunk&&n.updateChunk(f(),t)}d&&d(),o&&i(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),p){const e=()=>{t.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(c=mo(),o.removeEventListener('readystatechange',e))};o.addEventListener('readystatechange',e)}return o.responseType=m,o.send(),y},y={withBitrateReporting:t=>(n=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(c=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(S=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(d=t,y),send:g,abort:()=>{o&&(o.abort(),o=void 0),h=!0,d&&d()}};return y}class vo{constructor(t){this.intervals=[],this.currentRate=0,this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const 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 go{constructor(t,e,i,s,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=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=mo(),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=bo(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=mo()-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=mo()}_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=mo();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 yo{constructor(t){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=t,this.chunkRateEstimator=new vo(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=So(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=So(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(i=>{var s;const a=Boolean(t.error);console.log('Live HTMLVideoElement error','ignoring:',!a,{errorField:t.error,readyState:t.readyState,event:i,src:t.src}),this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,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 e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>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 go(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:a}=this.params;let r=!1,n=null,o=null,u=null,l=null,d=!1;const h=()=>{const t=r&&(!d||d===this.rep);return t||i('Not running!'),t},c=(t,e,i)=>{u&&u.abort(),u=bo(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==o||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{o=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=mo()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const a=this.bufferStates[i];t=Math.min(t,a.buf),a.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,m(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else m(1)},b=e=>{let s;const r=()=>s&&s.start?s.start.length:0,n=t=>s.start[t]/1e3,o=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,d=(t,e)=>({chunkIdx:u(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(s&&s.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,i=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=e;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=s.dur.length-1;for(;r>=0&&(a-=s.dur[r],!(a<=0));--r);t=Math.min(r,s.dur.length-1-i),t=Math.max(t,0)}return d(t,!0)},p=(t,e,i)=>{l&&l.abort(),l=bo(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{l=null})).withJSONResponse().send()};return{seek:(i,o)=>{p(e,(e=>{if(!h())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let l=0;for(let t=0;t<s.dur.length;++t)l+=s.dur[t];l>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(l/s.dur.length)),a({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=r();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(n(t)>e)return d(t);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=r(),a=t?t.chunkIdx+1:0,n=a-s.fragIndex;if(!(e<=0)){if(!t||n<0||n-e>10)return i(`Resync: offset=${n} bChunks=${e} chunk=`+JSON.stringify(t)),c();if(!(n>=e))return d(a-s.fragIndex,!1)}}}},v=()=>{r=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:i=>{const{videoElement:s,logger:a}=this.params;let o,u,d,m,f,g,y,T=b(e.jidxUrl),E=0;const k=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=mo(),s=Math.min(1e4,e-i);E=i;const a=()=>{l||h()&&T.seek((()=>{h()&&(E=mo(),w(),k())}))};s>0?f=window.setTimeout((()=>{this.paused?k():a()}),s):a()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(d);if(i){if(d&&i.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?k():(v(),this._initPlayerWith(e)));x(i)}else k()},P=(t,e)=>{if(!h()||!this.sourceBuffer)return;let i,r,n;const o=i=>{window.setTimeout((()=>{h()&&P(t,e)}),i)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),o(100);else{const u=mo(),l=s.currentTime;!this.paused&&s.buffered.length>1&&g===l&&u-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),g!==l&&(g=l,y=u);const d=this._getBufferSizeSec();if(d>30)a(`Buffered ${d} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:d}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;a('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(i=this.sourceBuffer.buffered.start(0),r=l,r-i>4&&this.sourceBuffer.remove(i,r-3)),o(1e3)}}},$=()=>{u&&o&&(a([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(d)]),P(u,(function(){u=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{h()&&p(A(t),((e,i)=>{if(h()){if(i/=1e3,u=e,d=t,n=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{h()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},R=t=>{h()&&(e.cachedHeader=t,P(t,(()=>{o=!0,$()})))};r=!0,T.seek((e=>{h()&&(E=mo(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(d=e,w())):k())}),i),e.cachedHeader?R(e.cachedHeader):c(e.headerUrl,R,(()=>this._handleNetworkError()))},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),t.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_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=mo();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&&fo(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=mo();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=bo(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;po(e).then((e=>{e||null==t||t()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return(null==t?void 0:t.length)?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var To;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(To||(To={}));const Eo=[To.PAUSED,To.PLAYING,To.READY],ko=[To.PAUSED,To.PLAYING,To.READY];class wo{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(To.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new Un,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new qn,this._dashCb=e=>{var i,s,a,r;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,r=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),a=null!==(s=co(e.name))&&void 0!==s?s:T(e.video),n=e.bitrate/1e3,o={...e.video};if(!a)continue;const u={id:t,quality:a,bitrate:n,size:o};r.push({track:u,representation:e})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),(null===(a=this.videoState.getTransition())||void 0===a?void 0:a.to)===To.MANIFEST_READY&&this.videoState.setState(To.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(r=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===r?void 0:r.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(n)};`}),a!==exports.PlaybackState.STOPPED){if(!s){if(ko.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===d.Requested&&Eo.includes(i))this.seek(n.position-this.liveOffset.getTotalPausedTime());else switch(i){case To.STOPPED:return this.videoState.startTransitionTo(To.MANIFEST_READY),void this.dash.attachSource(f(this.params.source.url));case To.MANIFEST_READY:this.videoState.startTransitionTo(To.READY),this.prepare();break;case To.READY:return void(a===exports.PlaybackState.PAUSED?this.videoState.setState(To.PAUSED):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(To.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(To.PAUSED)}))));case To.PLAYING:return void(a===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(To.PAUSED),this.liveOffset.pause(),this.dash.pause()));case To.PAUSED:return void(a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(To.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(To.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return t.assertNever(i)}}}else i!==To.STOPPED&&(this.videoState.startTransitionTo(To.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(To.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Fn(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ro(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Gn(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===To.READY&&this.videoState.setState(To.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(To.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===d.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(To.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(t.combine({zeroTime:this.zeroTime$.pipe(t.filter(t.isNonNullable)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)).add(On(this.video,this.params.desiredState.isLooped,i)).add(Bn(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(Mn(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,i)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&b[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case To.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case To.MANIFEST_READY:case To.READY:break;case To.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case To.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(e.to)}}),i)).add(t.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new yo({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var e,i,s,a,r,n;const o=this.representations$.getValue(),u=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),l=null!==(a=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==a?a:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!l&&t.isNonNullable(u)?u:null===(r=ao(o.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))||void 0===r?void 0:r.id,h=null===(n=o.find((({track:t})=>t.id===d)))||void 0===n?void 0:n.representation;t.assertNonNullable(h,'Representations missing'),this.dash.startPlay(h,l),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(d),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(l)}setVideoTrack(e){var i;const s=null===(i=this.representations$.getValue().find((({track:t})=>t.id===e)))||void 0===i?void 0:i.representation;t.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}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(f(this.params.source.url,i))}}var Po=t=>{var e,i;const s=t.get('X-Delivery-Type'),a=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===a?void 0:null!==(i={1:!0,0:!1}[a])&&void 0!==i?i:void 0}},$o=(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 Ao{constructor(t,e=[],i,s,a,r){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=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 e=!1;this._xhr.onreadystatechange=()=>{var i,s,a,r,n,o,u,l;if(t.assertNonNullable(this._xhr),(null===(i=this._xhr)||void 0===i?void 0:i.status)>=400)return null===(s=this._errorCb)||void 0===s||s.call(this,`Http${null===(a=this._xhr)||void 0===a?void 0:a.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Dn(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(n=this._headersCb)||void 0===n||n.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(o=this._completeCb)||void 0===o||o.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(u=this._progressCb)||void 0===u||u.call(this,this._xhr.response))}catch(t){throw null===(l=this._errorCb)||void 0===l||l.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class xo{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,n){this.abort((()=>{let o=0;const u=Date.now();let l=0,d=0,h=0;const c=t=>{s(xo._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=Cn(p)),this._lastXhr=new Ao(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(t);const e=Date.now()-u;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==a||a()}),(t=>{if(t.length-o>n&&c(t),0===d)return void(d=Date.now());h=t.length-l;const e=Date.now()-d;h>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:h,duration:e,speed:8*h/(e/1e3)}),h=0,l=t.length,d=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=xo._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class No{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=Cn(i)),new Ao(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=>{var s,o,u,l,d,h,c,p,m,f,S,b,v,g,y,T,E,k,w;const P=t.getElementsByTagName('SegmentBase')[0],$=P&&a(P,'indexRange').split('-'),A=P&&P.getElementsByTagName('Initialization')[0],x=A&&a(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const a=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,r=(i?i+'/':'')+(null===(d=null===(l=null===(u=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===u?void 0:u.childNodes)||void 0===l?void 0:l[0])||void 0===d?void 0:d.data),c=null!==(h=e.getAttribute('lang'))&&void 0!==h?h:void 0;r&&n.push({id:a,url:r,language:c})}return}const N=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const _=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=_?Yn(_):void 0,r.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(S=t.attributes.getNamedItem('height'))||void 0===S?void 0:S.value),bandwidth:N,baseURL:R,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(v=null===(b=t.attributes.getNamedItem('codecs'))||void 0===b?void 0:b.value)&&void 0!==v?v:void 0,mimeType:null!==(y=null===(g=t.attributes.getNamedItem('mimeType'))||void 0===g?void 0:g.value)&&void 0!==y?y:void 0,fps:D,bufferSize:.1*N/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==(w=null===(k=t.attributes.getNamedItem('id'))||void 0===k?void 0:k.value)&&void 0!==w?w: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 u=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;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 l=t.refs[t.refs.length-1];l.toTime-l.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 xo({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 e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const a=i[e];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Ro;!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'}(Ro||(Ro={}));const Do=[Ro.PAUSED,Ro.PLAYING];class _o{constructor(e){this.videoState=new k(Ro.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new Un,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},this.handleManifestReady=t=>{var e,i,s;const a=[];for(const r of t){const t=null!==(i=null!==(e=r.name)&&void 0!==e?e:r.id)&&void 0!==i?i:r.height.toString(10),n=null!==(s=r.name&&co(r.name))&&void 0!==s?s:T(r),o=r.bandwidth/1e3,u={width:r.width,height:r.height},l=r.fps;if(!n)continue;const d={id:t,quality:n,bitrate:o,size:u,fps:l};a.push({track:d,representation:r})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),this.videoState.setState(Ro.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)switch((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&r.state===d.Requested&&Do.includes(e)&&this.seek(r.position,r.forcePrecise),e){case Ro.STOPPED:return this.videoState.startTransitionTo(Ro.MANIFEST_LOADED),void this.prepare();case Ro.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Ro.INITIAL_REPRESENTATION_SELECTED);case Ro.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Ro.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Ro.METADATA_LOADED:return this.videoState.startTransitionTo(Ro.READY),void this.dash.updateRefsForCurrentTime();case Ro.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Ro.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ro.PLAYING),this.playIfAllowed()));case Ro.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ro.PAUSED),this.video.pause()):(null==a?void 0:a.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ro.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ro.PLAYING),this.playIfAllowed()):(null==a?void 0:a.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Ro.STOPPED&&(this.videoState.startTransitionTo(Ro.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(Ro.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Fn(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(ro(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new jn(this.video),this.dash=new No({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:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:t})},a=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},r=Gn(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,s));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.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),this.subscription.add(r.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekState.getState().state!==d.Applying)&&(this.videoState.getState()===Ro.PLAYING||this.videoState.getState()===Ro.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(On(this.video,i.isLooped,s)),this.subscription.add(Bn(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Mn(this.video,i.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),n(no(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Ro.READY&&this.videoState.setState(Ro.READY)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ro.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Ro.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Ro.METADATA_LOADED)}),s)).add(r.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(t.merge(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$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i,s;const r=this.currentRepresentation$.getValue(),n=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.videoTrack.getState(),l=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),d=this.elementSize$.getValue(),h=a();let c;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!h&&t.isNonNullable(u))c=u;else{const t=$o(this.video.buffered,1e3*this.video.currentTime),s=h?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(t/s,1);c=null===(i=ao(n.map((({track:t})=>t)),{container:d,throughput:l,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:null===(e=n.find((({representation:t})=>t===r)))||void 0===e?void 0:e.track}))||void 0===i?void 0:i.id}return t.isNonNullable(c)?null===(s=n.find((({track:t})=>t.id===c)))||void 0===s?void 0:s.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===Ro.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(Ro.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?t.height<=e.height:t===e))).subscribe((t=>{const e=$o(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!a())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(ro(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Po(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once(),t.mapTo(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(t.filter(t.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case'url':this.dash.attachSource(e.url);break;case'raw':this.dash.attachManifest(e.raw);break;default:return t.assertNever(e)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){po(this.video).then((t=>{t||(this.videoState.setState(Ro.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Co,Io,Lo,Oo,Bo;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(Co||(Co={})),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'}(Io||(Io={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(Lo||(Lo={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(Oo||(Oo={})),function(t){t.MP4='mp4',t.WEBM='webm'}(Bo||(Bo={}));var Mo=(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 Vo='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;var Uo,Fo,qo=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};let jo=!1;try{jo=qo()&&parseInt(null!==(Fo=null===(Uo=navigator.userAgent.match(/Version\/(\d+)/))||void 0===Uo?void 0:Uo[1])&&void 0!==Fo?Fo:'',10)<16}catch(t){console.error(t)}class Ho{constructor(e){this.bufferFull$=new t.Subject,this.error$=new t.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const e=null===(t=this.currentTask.signal)||void 0===t?void 0:t.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown:t})}},this.buffer=e,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=jo&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var t;if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(null===(t=e.signal)||void 0===t?void 0:t.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===i?this.bufferFull$.next(this.currentTask.data.byteLength):t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===i||this.error$.next({id:`BufferTaskQueue:${i}`,message:'Buffer operation failed',thrown:t}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(e){const{operation:i}=e;switch(i){case'append':this.buffer.appendBuffer(e.data);break;case'remove':this.buffer.remove(e.from/1e3,e.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(e.init);break;default:t.assertNever(i)}}}var Go,Yo=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'}(Go||(Go={}));class Qo{constructor({throughputEstimator:e,requestQuic:i}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new C,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=Cn(e));const i=yield _(e,{signal:this.abortAllController.signal}).catch(zo);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetch=t.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:i=Go.HEADER,range:s,onProgress:a,priority:r='auto',signal:n,measureThroughput:o=!0}={}){var u,l,d,h;let c=e;const p=new Headers;if(s)switch(i){case Go.HEADER:p.append('Range',`${s.from}-${s.to}`);break;case Go.PARAM:{const t=new URL(c,location.href);t.searchParams.append('bytes',`${s.from}-${s.to}`),c=t.toString();break}default:t.assertNever(i)}this.requestQuic&&(c=Cn(c));let m=this.abortAllController.signal;if(n){const e=new C;if(this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(n,'abort')).subscribe((()=>{try{e.abort()}catch(t){zo(t)}}))),this.abortAllController.signal.aborted||n.aborted)try{e.abort()}catch(t){zo(t)}m=e.signal}const f=t.now(),S=yield _(c,{priority:r,headers:p,signal:m}).catch(zo),b=t.now();if(null===(u=this.throughputEstimator)||void 0===u||u.addRawRtt(b-f),!S)return null;if(!S.ok||!S.body)return Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));this.onHeadersReceived(S.headers);const v=parseInt(null!==(l=S.headers.get('Content-Length'))&&void 0!==l?l:'',10)||s&&s.to-s.from+1||NaN;if(!v){const e=yield S.arrayBuffer();return null===(d=this.throughputEstimator)||void 0===d||d.addRawSpeed(e.byteLength,t.now()-b),null==a||a(new DataView(e),e.byteLength),e}if(!a&&!o)return S.arrayBuffer();const[g,y]=S.body.tee(),T=g.getReader();o&&(null===(h=this.throughputEstimator)||void 0===h||h.trackStream(y));let E=0;const k=new ArrayBuffer(v),w=new Uint8Array(k),P=new DataView(k);let $=!1;const A=t=>{$=!0,zo(t)},x=t.abortable(m,async function*({done:e,value:i}){0===E&&this.lastRequestFirstBytes$.next(t.now()-f),m.aborted||(e?null==a||a(P,E):i&&(w.set(i,E),E+=i.byteLength,null==a||a(P,E),yield null==T?void 0:T.read().then(x,A)))}.bind(this));return yield null==T?void 0:T.read().then(x,A),$?null:k}.bind(this)),this.fetchByteRangeRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e,i){if(t.type!==Lo.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,n,o=s,u=a,l=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,l=a+1===r,l&&(o=Math.min(r,s),u=Math.max(n,a))),o=Math.min(o,0);const d=yield this.fetch(t.url,{rangeMethod:Go.PARAM,range:{from:o,to:u},priority:i,measureThroughput:!1});if(!d)return null;const h=new DataView(d,s-o,a-o+1);if(!e.validateData(h))throw new Error('Invalid media file');const c=e.parseInit(h);let p;if(l&&void 0!==r&&void 0!==n)p=new DataView(d,r-o,n-r+1);else{const s=e.getIndexRange(c);if(s){const e=yield this.fetch(t.url,{rangeMethod:Go.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,c);return{dataView:new DataView(d),segments:m}}.bind(this)),this.fetchTemplateRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e){if(t.type!==Lo.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:Oo.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=Po(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,i,s='auto'){var a,r;const{type:n}=e;switch(n){case Lo.BYTE_RANGE:return null!==(a=await this.fetchByteRangeRepresentation(e,i,s))&&void 0!==a?a:null;case Lo.TEMPLATE:return null!==(r=await this.fetchTemplateRepresentation(e,s))&&void 0!==r?r:null;default:t.assertNever(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const zo=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Wo=new TextDecoder('ascii'),Jo=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=Wo.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)}},Xo={validateData:t=>'ftyp'===Wo.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Jo(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(),u=4294967295&a();let l=n/r*1e3,d=t.byteOffset+t.byteLength+o;for(let t=0;t<u;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:Oo.NONE,time:{from:l,to:l+o},byte:{from:d,to:d+s-1}}),l+=o,d+=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=Jo(a);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var Ko,Zo;!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'}(Ko||(Ko={})),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'}(Zo||(Zo={}));const tu={[Ko.EBML]:{type:Zo.Master},[Ko.EBMLVersion]:{type:Zo.UnsignedInteger},[Ko.EBMLReadVersion]:{type:Zo.UnsignedInteger},[Ko.EBMLMaxIDLength]:{type:Zo.UnsignedInteger},[Ko.EBMLMaxSizeLength]:{type:Zo.UnsignedInteger},[Ko.DocType]:{type:Zo.String},[Ko.DocTypeVersion]:{type:Zo.UnsignedInteger},[Ko.DocTypeReadVersion]:{type:Zo.UnsignedInteger},[Ko.Void]:{type:Zo.Binary},[Ko.Segment]:{type:Zo.Master},[Ko.SeekHead]:{type:Zo.Master},[Ko.Seek]:{type:Zo.Master},[Ko.SeekID]:{type:Zo.Binary},[Ko.SeekPosition]:{type:Zo.UnsignedInteger},[Ko.Info]:{type:Zo.Master},[Ko.TimestampScale]:{type:Zo.UnsignedInteger},[Ko.Duration]:{type:Zo.Float},[Ko.Tracks]:{type:Zo.Master},[Ko.Chapters]:{type:Zo.Master},[Ko.Cluster]:{type:Zo.Master},[Ko.Timestamp]:{type:Zo.UnsignedInteger},[Ko.SilentTracks]:{type:Zo.Master},[Ko.SilentTrackNumber]:{type:Zo.UnsignedInteger},[Ko.Position]:{type:Zo.UnsignedInteger},[Ko.PrevSize]:{type:Zo.UnsignedInteger},[Ko.SimpleBlock]:{type:Zo.Binary},[Ko.BlockGroup]:{type:Zo.Master},[Ko.EncryptedBlock]:{type:Zo.Binary},[Ko.Attachments]:{type:Zo.Master},[Ko.Tags]:{type:Zo.Master},[Ko.Cues]:{type:Zo.Master},[Ko.CuePoint]:{type:Zo.Master},[Ko.CueTime]:{type:Zo.UnsignedInteger},[Ko.CueTrackPositions]:{type:Zo.Master},[Ko.CueTrack]:{type:Zo.UnsignedInteger},[Ko.CueClusterPosition]:{type:Zo.UnsignedInteger},[Ko.CueRelativePosition]:{type:Zo.UnsignedInteger},[Ko.CueDuration]:{type:Zo.UnsignedInteger},[Ko.CueBlockNumber]:{type:Zo.UnsignedInteger},[Ko.CueCodecState]:{type:Zo.UnsignedInteger},[Ko.CueReference]:{type:Zo.Master},[Ko.CueRefTime]:{type:Zo.UnsignedInteger}},eu=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=iu(t,i),a=s in tu,r=a?tu[s].type:Zo.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 u=new DataView(t.buffer,t.byteOffset+i+1,o-1),l=((n&255>>o)<<8*(o-1))+iu(u),d=i+o;let h;return h=d+l>t.byteLength?new DataView(t.buffer,t.byteOffset+d):new DataView(t.buffer,t.byteOffset+d,l),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:d,tagSize:d+l,value:h,valueSize:l}},iu=(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},su=(e,i)=>{switch(i){case Zo.SignedInteger:return e.getInt8(0);case Zo.UnsignedInteger:return iu(e);case Zo.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case Zo.String:return new TextDecoder('ascii').decode(e);case Zo.UTF8:return new TextDecoder('utf-8').decode(e);case Zo.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case Zo.Master:case Zo.Binary:return e;default:t.assertNever(i)}},au=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=eu(s);if(!e(a))return;a.type===Zo.Master&&au(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},ru=[Ko.Info,Ko.SeekHead,Ko.Tracks,Ko.Chapters,Ko.Cluster,Ko.Cues,Ko.Attachments,Ko.Tags],nu=[Ko.Timestamp,Ko.SilentTracks,Ko.SilentTrackNumber,Ko.Position,Ko.PrevSize,Ko.SimpleBlock,Ko.BlockGroup,Ko.EncryptedBlock],ou={validateData:t=>{if(t.getUint32(0)!==Ko.EBML)return!1;let e,i,s;const a=eu(t);return au(a.value,(({tag:t,type:a,value:r})=>(t===Ko.EBMLReadVersion?e=su(r,a):t===Ko.DocType?i=su(r,a):t===Ko.DocTypeReadVersion&&(s=su(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,a,r,n,o,u=!1,l=!1,d=!1;return au(e,(({tag:t,type:e,value:h,valueSize:c})=>{if(t===Ko.SeekID){const t=su(h,e);o=iu(t)}else t!==Ko.SeekPosition&&(o=void 0);return t===Ko.Segment?(i=h.byteOffset,s=h.byteOffset+c):t===Ko.Info?u=!0:t===Ko.SeekHead?l=!0:t===Ko.TimestampScale?a=su(h,e):t===Ko.Duration?r=su(h,e):t===Ko.SeekPosition&&o===Ko.Cues?n=su(h,e):u&&l&&ru.includes(t)&&(d=!0),!d})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(r,'Failed to parse webm Segment duration'),a=null!=a?a:1e6,{segmentStart:Math.round(i/1e9*a*1e3),segmentEnd:Math.round(s/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:n}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,a=!1;const r=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),n=[];let o;return au(e,(({tag:t,type:e,value:i})=>{switch(t){case Ko.Cues:s=!0;break;case Ko.CuePoint:o&&r(o)&&n.push(o),o={};break;case Ko.CueTime:o&&(o.time=su(i,e));break;case Ko.CueTrackPositions:break;case Ko.CueClusterPosition:o&&(o.position=su(i,e));break;default:s&&ru.includes(t)&&(a=!0)}return!(s&&a)})),o&&r(o)&&n.push(o),n.map(((t,e)=>{const{time:s,position:a}=t,r=n[e+1];return{status:Oo.NONE,time:{from:s,to:r?r.time:i.segmentDuration},byte:{from:i.segmentStart+a,to:r?i.segmentStart+r.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{au(t,(s=>s.tag===Ko.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!nu.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[Ko.SimpleBlock,Ko.BlockGroup,Ko.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class uu{constructor(e,i,s,a,{fetcher:r,tuning:n,getCurrentPosition:o}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new C,this.destroyAbortController=new C,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=t.abortable(this.destroyAbortController.signal,async function*(e){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.sourceBufferTaskQueue=new Ho(this.sourceBuffer),this.subscription.add(t.fromEvent(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(t.fromEvent(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,Yo(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield this.loadInit(i,'high',!0);const s=this.initData.get(i.id),a=this.segments.get(i.id);if(t.assertNonNullable(s,'No init buffer for starting representation'),t.assertNonNullable(a,'No segments for starting representation'),!(s instanceof ArrayBuffer))return;let r=0;for(const t of a)t.time.from-r>=300&&this.gaps.push({representation:i.id,from:r,to:t.time.from}),r=t.time.to;t.isNonNullable(i.duration)&&i.duration-r>=300&&this.gaps.push({representation:i.id,from:r,to:i.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const i=this.representations.get(e);t.assertNonNullable(i,`No such representation ${e}`);let s=this.initData.get(e);if(t.isNullable(s)?yield this.loadInit(i,'high',!1):s instanceof Promise&&(yield s),s=this.initData.get(e),!(s&&s instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();t.isNonNullable(a)&&this.maintain(a)}.bind(this)),this.fetcher=r,this.tuning=n,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case Bo.MP4:this.containerParser=Xo;break;case Bo.WEBM:this.containerParser=ou;break;default:t.assertNever(s)}this.initData=new Map(a.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(a.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new C,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer))return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(t.assertNonNullable(i,`No such representation ${this.downloadingRepresentationId}`),!s)return;const a=s.find((t=>e>=t.time.from&&e<t.time.to));let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=100,i=$o(this.sourceBuffer.buffered,e),s=a?a.time.to+t:-1/0;a&&i>=a.time.to-e+t&&(r=s)}if(isFinite(this.bufferLimit)&&Yo(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),a&&a.status!==Oo.NONE))return;let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(s,i.segmentReference.type,r),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&a)if(n.includes(a))t='high';else{const e=Jn(n,0);e&&e.time.from-a.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,i,t)}!this.allInitsLoaded&&a&&a.status===Oo.FED&&!n.length&&$o(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const o=Jn(s,-1);o&&o.status===Oo.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===o))}findSegmentStartTime(t){var e,i,s;const a=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!a)return;const r=this.segments.get(a);if(!r)return;const n=r.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===Oo.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==Lo.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!==Oo.NONE&&e.status!==Oo.PARTIALLY_EJECTED)break;n.push(e)}return n}async loadSegments(e,i,s='auto'){if(!e.length)return;let a,r,n=e;const{type:o}=i.segmentReference;switch(o){case Lo.BYTE_RANGE:a=i.segmentReference.url,r={from:Jn(e,0).byte.from,to:Jn(e,-1).byte.to};break;case Lo.TEMPLATE:{const t=Jn(e,0);a=new URL(t.url,i.segmentReference.baseUrl).toString(),n=[t];break}default:t.assertNever(o)}for(const t of n)t.status=Oo.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:i.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await t.abortable(u,async function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((t=>setTimeout(t,e)))}.bind(this))(),u.aborted))for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.fetcher.fetch(a,{rangeMethod:Go.PARAM,range:r,onProgress:(t,e)=>{if(!u.aborted)try{this.onSomeDataLoaded(t,i.id,r?r.from:0,e,u)}catch(t){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:t})}},signal:u,priority:s}).then((()=>this.failedDownloads=0),(t=>{for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.onSegmentDownloadError(t)}))}onSegmentDownloadError(e){var i;let s=!1;const a=this.getCurrentPosition();if(this.sourceBuffer&&t.isNonNullable(a)){s=$o(null===(i=this.sourceBuffer)||void 0===i?void 0:i.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,s||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:e})}onSomeDataLoaded(t,e,i,s,a){if(!this.activeSegments.size)return;const r=t=>{this.abortSegment(t.segment)},n=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=Oo.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===Oo.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=Oo.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const u=o.segmentReference.type,l=t.byteLength;for(const o of this.activeSegments){const{segment:d}=o,h=u===Lo.BYTE_RANGE,c=h?d.byte.to-d.byte.from+1:l;if(o.representationId!==e)continue;if(!(!h||d.byte.from>=i&&d.byte.to<i+t.byteLength))continue;if(a.aborted){r(o);continue}const p=h?d.byte.from-i:0,m=p<s,f=(h?d.byte.to-i:t.byteLength)<=s;if(d.status===Oo.DOWNLOADING&&m&&f){d.status=Oo.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,c);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(c,s-p),o.loadedBytes>o.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),i=o.loadedBytes===c?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(d.status=Oo.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===c&&n(o);else{if(o.feedingBytes<c)return;r(o)}})))}}}abortSegment(t){t.status===Oo.PARTIALLY_FED||t.status===Oo.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=Oo.NONE)),t.status=Oo.PARTIALLY_EJECTED):t.status=Oo.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||(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=Vo((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(e,i='auto',s=!1){const a=this.tuning.dash.useFetchPriorityHints?i:'auto',r=(!s&&this.failedDownloads>0?t.abortable(this.destroyAbortController.signal,async function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((t=>setTimeout(t,e)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a))).then((t=>{if(!t)return;const{dataView:i,segments:s}=t,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(e.id,a),this.segments.set(e.id,s)})).then((()=>this.failedDownloads=0),(t=>{this.initData.set(e.id,null),s&&this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:t})}));return this.initData.set(e.id,r),r}async pruneBuffer(e){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let a=0,r=1/0,n=-1/0,o=!1;const u=t=>{var e;r=Math.min(r,t.time.from),n=Math.max(n,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;a+=i};for(const t of s){if(t.time.to>=i||a>=e)break;t.status===Oo.FED&&u(t)}if(o=isFinite(r)&&isFinite(n),!o){a=0,r=1/0,n=-1/0;for(const t of s){if(t.time.from<i+this.forwardBufferTarget||a>e)break;t.status===Oo.FED&&u(t)}}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),i=1e3*this.sourceBuffer.buffered.end(t);for(const t of s)if(t.status===Oo.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(i)){r=e,n=i;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=Vo((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=Math.round(1e3*this.sourceBuffer.buffered.start(t)),s=Math.round(1e3*this.sourceBuffer.buffered.end(t));e.push({from:i,to:s})}for(const t of this.segments.values())for(const i of t){const{status:t}=i;if(t!==Oo.FED&&t!==Oo.PARTIALLY_EJECTED)continue;const s=Math.round(i.time.from),a=Math.round(i.time.to),r=e.some((t=>t.from<=s&&t.to>=a)),n=e.some((t=>s>t.from&&s<t.to||a>t.from&&a<t.to));r||(i.status=n?Oo.PARTIALLY_EJECTED:Oo.NONE)}}}const lu=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},du=(e,i)=>{let s=e;s=s.replaceAll('$$','$');const a={RepresentationID:i.representationId,Number:i.segmentNumber,Bandwidth:i.bandwidth,Time:i.segmentTime};for(const[e,i]of Object.entries(a)){const a=new RegExp(`\\$${e}(?:%0(\\d+)d)?\\$`,'g');s=s.replaceAll(a,((e,s)=>t.isNullable(i)?e:t.isNullable(s)?i:i.padStart(parseInt(s,10),'0')))}return s},hu=['timeupdate','progress','play','seeked','stalled'];var cu,pu;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(cu||(cu={}));class mu{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new k(cu.NONE),this.currentVideoRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.forceEnded$=new t.Subject,this.gapWatchdogStarted=!1,this.destroyController=new C,this.initManifest=t.abortable(this.destroyController.signal,async function*(e,i){this.element=e,this.state$.startTransitionTo(cu.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(i).catch((t=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:t})));if(!s)return null;let a;try{a=((e,i)=>{var s,a,r,n,o,u,l,d,h,c,p,m,f,S,b,v,g,y,T,E,k,w,P,$,A,x,N,R,D,_,C,I,L,O,B;const M={video:[],audio:[],text:[]},V=(new DOMParser).parseFromString(e,'application/xml').children[0],U=V.getElementsByTagName('Period')[0],F=U.children;let q;const j=V.getAttribute('mediaPresentationDuration'),H=U.getAttribute('duration');if(j)q=lu(j);else if(H){const e=lu(H);t.isNonNullable(e)&&(q=e)}let G=0;const Y=null!==(a=null===(s=V.getAttribute('profiles'))||void 0===s?void 0:s.split(','))&&void 0!==a?a:[],Q=Y.includes(Io.WEBM_AS_IN_FFMPEG)||Y.includes(Io.WEBM_AS_IN_SPEC)?Bo.WEBM:Bo.MP4;for(const t of F){const e=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),a=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==e?void 0:e.split('/')[0],V=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],U=t.querySelectorAll('Representation');if('text'!==a)for(const r of U){const n=null!==(u=r.getAttribute('mimeType'))&&void 0!==u?u:e,o=null!==(d=null!==(l=r.getAttribute('codecs'))&&void 0!==l?l:s)&&void 0!==d?d:'',U=null!==(c=null!==(h=r.getAttribute('contentType'))&&void 0!==h?h:null==n?void 0:n.split('/')[0])&&void 0!==c?c:a,F=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],j=parseInt(null!==(f=r.getAttribute('width'))&&void 0!==f?f:'',10),H=parseInt(null!==(S=r.getAttribute('height'))&&void 0!==S?S:'',10),Q=parseInt(null!==(b=r.getAttribute('bandwidth'))&&void 0!==b?b:'',10)/1e3,z=null!==(v=r.getAttribute('frameRate'))&&void 0!==v?v:'',W=null!==(g=r.getAttribute('quality'))&&void 0!==g?g:void 0,J=z?Yn(z):void 0,X=`${null!==(y=r.getAttribute('id'))&&void 0!==y?y:(G++).toString(10)}@${'video'===U?`${H}p`:'audio'===U?`${Q}Kbps`:o}`,K=null!==(k=null===(E=null===(T=r.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==k?k:'',Z=new URL(K,i).toString(),tt=[...Y,...V,...F];let et;const it=r.querySelector('SegmentBase'),st=r.querySelector('SegmentTemplate');if(it){const t=null!==(P=null===(w=r.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==P?P:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=null===($=r.querySelector('SegmentBase'))||void 0===$?void 0:$.getAttribute('indexRange'),[n,o]=a?a.split('-').map((t=>parseInt(t,10))):[],u=a?{from:n,to:o}:void 0;et={type:Lo.BYTE_RANGE,url:Z,initRange:s,indexRange:u}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(A=r.getAttribute('id'))&&void 0!==A?A:void 0,bandwidth:null!==(x=r.getAttribute('bandwidth'))&&void 0!==x?x:void 0},e=parseInt(null!==(N=st.getAttribute('timescale'))&&void 0!==N?N:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),a=null!==(_=parseInt(null!==(D=st.getAttribute('startNumber'))&&void 0!==D?D:'',10))&&void 0!==_?_:1,n=du(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const o=null!==(C=st.querySelectorAll('SegmentTimeline S'))&&void 0!==C?C:[],u=[];let l=a,d=0;for(const i of o){const a=1e3*parseInt(null!==(I=i.getAttribute('d'))&&void 0!==I?I:'',10),r=parseInt(null!==(L=i.getAttribute('r'))&&void 0!==L?L:'',10)||0,n=null!==(B=parseInt(null!==(O=i.getAttribute('t'))&&void 0!==O?O:'',10))&&void 0!==B?B:void 0;for(let i=0;i<r+1;i++){const i=du(s,{...t,segmentNumber:l.toString(10),segmentTime:n.toString(10)}),r=n?n/e:d;d+=a/e;const o=d;l++,u.push({time:{from:r,to:o},url:i})}}et={type:Lo.TEMPLATE,baseUrl:Z,initUrl:n,segments:u}}}if(!U||!n)continue;const at={video:Co.VIDEO,audio:Co.AUDIO,text:Co.TEXT}[U];at&&M[at].push({id:X,kind:at,segmentReference:et,profiles:tt,duration:q,bitrate:Q,mime:n,codecs:o,width:j,height:H,fps:J,quality:W})}}return{duration:q,container:Q,representations:M}})(null!=s?s:'',i)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!a)return null;const r=({mime:t,codecs:i})=>{var s,a,r;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(r=null===(a=window.MediaSource)||void 0===a?void 0:a.isTypeSupported)||void 0===r?void 0:r.call(a,`${t}; codecs="${i}"`)))};return this.manifest={...a,representations:Dn(Object.entries(a.representations).map((([t,e])=>[t,e.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(cu.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,async function*(e,i){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(cu.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new uu(Co.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],t.isNonNullable(i)&&(this.audioBufferManager=new uu(Co.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=t.merge(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(t.map((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),r=t.merge(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(t.map((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(t.merge(this.forceEnded$,t.combine({allBuffersFull:a,someBufferEnded:r}).pipe(t.filter((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var t;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(t.merge(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)}))),t.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&t.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(e),this.state$.setState(cu.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...hu.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&Mo(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this)),this.tick=()=>{var e,i;if(!this.element||!this.videoBufferManager)return;const s=1e3*this.element.currentTime;this.videoBufferManager.maintain(s),null===(e=this.audioBufferManager)||void 0===e||e.maintain(s),!this.videoBufferManager.gaps.length&&!(null===(i=this.audioBufferManager)||void 0===i?void 0:i.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Qo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(t,e){const i={[Co.VIDEO]:this.videoBufferManager,[Co.AUDIO]:this.audioBufferManager,[Co.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}seek(e,i){var s,a,r,n,o;let u;t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),u=i||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(null!==(s=this.videoBufferManager.findSegmentStartTime(e))&&void 0!==s?s:e,null!==(r=null===(a=this.audioBufferManager)||void 0===a?void 0:a.findSegmentStartTime(e))&&void 0!==r?r:e),Mo(this.element.buffered,u)||(this.videoBufferManager.abort(),null===(n=this.audioBufferManager)||void 0===n||n.abort()),this.videoBufferManager.maintain(u),null===(o=this.audioBufferManager)||void 0===o||o.maintain(u),this.element.currentTime=u/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(cu.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of this.bufferManagers)for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(pu||(pu={}));const fu=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{var n;const o=null!==(n=r?co(r):void 0)&&void 0!==n?n:T({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:a}},Su=(t,e,i)=>{var s;const a=e.indexOf(i);return null!==(s=Jn(t,Math.round(t.length*a/e.length)))&&void 0!==s?s:Jn(t,-1)};class bu{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(pu.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new Un,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new so,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(a.state===d.Requested&&(null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&e!==pu.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),i!==exports.PlaybackState.STOPPED){if(e===pu.STOPPED)return this.videoState.startTransitionTo(pu.READY),void this.prepare();switch(e){case pu.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(pu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(pu.PLAYING),this.playIfAllowed()));case pu.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(pu.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case pu.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(pu.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==pu.STOPPED&&(this.videoState.startTransitionTo(pu.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(pu.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=Fn(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ro(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new mu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=Gn(this.video),a=t=>{e.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:t})},r=(t,e)=>this.subscription.add(t.subscribe(e,a));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once(),t.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(On(this.video,i.isLooped,a)),this.subscription.add(Bn(this.video,i.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Mn(this.video,i.playbackRate,s.playbackRateState$,a)),r(no(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(pu.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),a)).add(s.pause$.subscribe((()=>{this.videoState.setState(pu.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),a)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===pu.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===cu.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(pu.READY)})));const n=t=>e.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:t});this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var s,a,r,o,u,l,d,h;const c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c===cu.NONE||!this.videoTracks.length)return;const m=c===cu.MANIFEST_LOADED&&!p,f=c===cu.REPRESENTATION_SELECTED&&!p,S=i.autoVideoTrackSwitching.getState(),b=i.videoTrack.getState(),v=null===(s=this.videoTracks.find((({track:{id:t}})=>t===b)))||void 0===s?void 0:s.track,g=e.currentVideoTrack$.getValue(),y=$o(this.video.buffered,1e3*this.video.currentTime),T=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),k=Math.max(v&&!S&&null!==(r=null===(a=this.audioRepresentations.get(v.id))||void 0===a?void 0:a.bitrate)&&void 0!==r?r:0,g&&null!==(u=null===(o=this.audioRepresentations.get(g.id))||void 0===o?void 0:o.bitrate)&&void 0!==u?u:0),w=ao(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),reserve:k,forwardBufferHealth:E,current:g,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),P=S?null!=w?w:v:null!=v?v:w;if(i.autoVideoTrackSwitching.getTransition()&&(i.autoVideoTrackSwitching.setState(S),this.player.setBufferTarget(T)),m){const e=P&&(null===(l=this.videoTracks.find((({track:t})=>t===P)))||void 0===l?void 0:l.representation);t.assertNonNullable(e),this.player.initRepresentations(e.id,null===(d=this.audioRepresentations.get(e.id))||void 0===d?void 0:d.id)}else if(f){const t=P&&(null===(h=this.videoTracks.find((({track:t})=>t===P)))||void 0===h?void 0:h.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(Co.VIDEO,t.id).catch(n),e&&this.player.switchRepresentation(Co.AUDIO,e.id).catch(n)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.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=fu(t);if(s){this.videoTracks.push({track:s,representation:t});const a=Su(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)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){po(this.video).then((t=>{t||(this.videoState.setState(pu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const vu={};var gu;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(gu||(gu={}));const yu=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class Tu{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(gu.INITIALIZING),this.textTracksManager=new Un,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!==gu.INITIALIZING)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===d.Requested&&this.seek(a.position),i){case exports.PlaybackState.STOPPED:switch(e){case gu.STOPPED:break;case gu.READY:case gu.PLAYING:case gu.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case gu.PLAYING:break;case gu.STOPPED:this.prepare();break;case gu.READY:case gu.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case gu.PAUSED:break;case gu.STOPPED:this.prepare();break;case gu.READY:this.videoState.setState(gu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case gu.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Fn(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ro(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);Promise.resolve().then((function(){return i(require('hls.js'))})).then((e=>{t||(vu.Hls=e.default,vu.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(vu.Hls,'hls.js not loaded'),this.hls=new vu.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(gu.STOPPED)}subscribe(){t.assertNonNullable(vu.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=t=>{i.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=Gn(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,i.position$),r(a.durationChange$,i.duration$),r(a.ended$,i.endedEvent$),r(a.looped$,i.loopedEvent$),r(a.error$,i.error$),r(a.isBuffering$,i.isBuffering$),r(a.currentBuffer$,i.currentBuffer$),r(a.loadStart$,i.firstBytesEvent$),r(a.playing$,i.firstFrameEvent$),r(a.canplay$,i.canplay$),r(a.seeked$,i.seekedEvent$),this.subscription.add(On(this.video,e.isLooped,s)),this.subscription.add(Bn(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Mn(this.video,e.playbackRate,a.playbackRateState$,s)),this.subscription.add(yu(this.hls,vu.Events.ERROR).subscribe((t=>{var e;t.fatal&&i.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(e=t.err)||void 0===e?void 0:e.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(gu.PLAYING),S(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(gu.PAUSED),S(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===gu.READY&&this.videoState.setState(gu.READY),this.videoState.getState()===gu.PLAYING&&this.playIfAllowed()}),s)),r(yu(this.hls,vu.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const a=e.name||e.height.toString(10),{width:r,height:n}=e,o=null!==(s=co(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:T({width:r,height:n});if(!o)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,l={id:a.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:r,height:n},fps:u};return this.trackLevels.set(a,{track:l,level:e}),t.push(l),t}),[])))),i.availableVideoTracks$),r(yu(this.hls,vu.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>ro(t)))),i.hostname$),this.subscription.add(Ln(e.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const n=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},o=yu(this.hls,vu.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>n(this.hls.levels[t]))));o.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(Ln(e.videoTrack,(()=>{var t;return null===(t=n(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const a=this.hls.levels.indexOf(s),r=this.hls.currentLevel,n=this.hls.levels[r];!n||s.bitrate>n.bitrate?this.hls.nextLevel=a:(this.hls.loadLevel=a,this.hls.loadLevel=a)}),{changed$:o.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(gu.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(gu.PLAYING);await po(this.video)||(this.videoState.setState(gu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(gu.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(gu.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}var Eu=async t=>{const e=await _(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0};const ku=t=>{let e=null;if(t.QUALITY&&(e=co(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=T({width:i,height:s})}return null!=e?e:null},wu=async(t,e=t)=>{var i;const s=await _(t),a=(await s.text()).split('\n'),r=[];for(let t=0;t<a.length;t++){const s=a[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=Dn(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,u=ku(n);let l;n.BANDWIDTH&&(l=parseInt(n.BANDWIDTH,10)/1e3||void 0),!l&&n['AVERAGE-BANDWIDTH']&&(l=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const d=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let h;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(h={width:t,height:e})}const c=new URL(a[++t],e).toString();u&&r.push({id:o,quality:u,url:c,bandwidth:l,size:h,fps:d})}return r};var Pu,$u,Au;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Pu||(Pu={}));class xu{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new k(Pu.STOPPED),this.textTracksManager=new Un,this.manifests$=new t.ValueSubject([]),this.liveOffset=new qn,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Pu.STOPPED&&(this.videoState.startTransitionTo(Pu.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(Pu.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===Pu.STOPPED)return this.videoState.startTransitionTo(Pu.READY),void this.prepare();if(a||r){const t=this.videoState.getState();return this.videoState.setState(Pu.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(n.state===d.None&&this.params.desiredState.seekState.setState({state:d.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===d.Requested)return this.videoState.startTransitionTo(Pu.READY),this.seek(n.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(e){case Pu.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Pu.PAUSED),this.liveOffset.pause(),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Pu.PLAYING),this.playIfAllowed()));case Pu.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Pu.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Pu.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Pu.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Pu.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Fn(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),wu(f(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ro(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),n=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=a?'master':n;return a&&!r&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:t})},a=Gn(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.ended$,e.endedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(Bn(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Mn(this.video,i.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Pu.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Pu.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Pu.READY&&this.videoState.setState(Pu.READY),this.videoState.getState()===Pu.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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(ro(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===Pu.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&e.state===d.Requested&&this.seek(e.position)}),s)),this.subscription.add(a.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=f(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',i),this.video.load(),Eu(i).then((e=>{var s;if(t.isNullable(e)){const e=null!==(s=this.params.source.maxSeekBackTime)&&void 0!==s?s:this.maxSeekBackTime$.getValue();if(t.isNullable(e)||!isFinite(e))try{_(i).then((t=>t.text())).then((e=>{var s;const a=null===(s=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(e))||void 0===s?void 0:s[1];if(a){const e=new URL(a,i).toString();Eu(e).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(e)}))}playIfAllowed(){po(this.video).then((t=>{t||(this.videoState.setState(Pu.PAUSED),this.liveOffset.pause(),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}($u||($u={}));class Nu{constructor(e){this.subscription=new t.Subscription,this.videoState=new k($u.STOPPED),this.textTracksManager=new Un,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==$u.STOPPED&&(this.videoState.startTransitionTo($u.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($u.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===$u.STOPPED)return this.videoState.startTransitionTo($u.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState($u.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(n.state===d.None&&this.params.desiredState.seekState.setState({state:d.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===d.Requested&&this.seek(n.position),e){case $u.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState($u.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($u.PLAYING),this.playIfAllowed()));case $u.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo($u.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case $u.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo($u.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case $u.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Fn(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ro(this.params.source.url)),wu(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.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),n=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=a?'master':n;return a&&!r&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:t})},a=Gn(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),r(a.seeked$,e.seekedEvent$),this.subscription.add(On(this.video,i.isLooped,s)),this.subscription.add(Bn(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Mn(this.video,i.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState($u.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState($u.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===$u.READY&&this.videoState.setState($u.READY),this.videoState.getState()===$u.PLAYING&&this.playIfAllowed()}),s).add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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(ro(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===$u.CHANGING_MANIFEST&&this.videoState.setState(i.to),e.state===d.Requested&&this.seek(e.position)}),s))),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){po(this.video).then((t=>{t||(this.videoState.setState($u.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Au||(Au={}));class Ru{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(Au.STOPPED),this.trackUrls={},this.textTracksManager=new Un,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Au.STOPPED&&(this.videoState.startTransitionTo(Au.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(Au.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(e===Au.STOPPED)return this.videoState.startTransitionTo(Au.READY),void this.prepare();if(a){const{currentTime:t}=this.video;return this.prepare(),void(r.state===d.None&&this.params.desiredState.seekState.setState({state:d.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===d.Requested&&this.seek(r.position),e){case Au.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Au.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Au.PLAYING),this.playIfAllowed()));case Au.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Au.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Au.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Au.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=Fn(e.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:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:t})},a=Gn(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),r(a.seeked$,e.seekedEvent$),this.subscription.add(On(this.video,i.isLooped,s)),this.subscription.add(Bn(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Mn(this.video,i.playbackRate,a.playbackRateState$,s)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Au.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Au.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===Au.READY&&this.videoState.setState(Au.READY);const i=this.params.desiredState.videoTrack.getTransition();i&&t.isNonNullable(i.to)&&(this.params.desiredState.videoTrack.setState(i.to),this.params.output.currentVideoTrack$.next(this.trackUrls[i.to].track)),this.videoState.getState()===Au.PLAYING&&this.playIfAllowed()}),s)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:a}=this.trackUrls[s];t.assertNonNullable(a,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(a=Cn(a)),this.video.setAttribute('src',a),this.video.load(),this.params.output.hostname$.next(ro(a))}playIfAllowed(){po(this.video).then((t=>{t||(this.videoState.setState(Au.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}const Du=['stun:videostun.mycdn.me:80'],_u=()=>null;class Cu{constructor(t,e){this.ws=null,this.peerConnection=null,this.serverUrl='',this.streamKey='',this.stream=null,this.signalingType='JOIN',this.retryCount=0,this.externalStartCallback=_u,this.externalStopCallback=_u,this.externalErrorCallback=_u,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:Du}]};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:Du,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var Iu,Lu,Ou,Bu,Mu,Vu,Uu,Fu,qu,ju,Hu,Gu,Yu,Qu,zu,Wu,Ju,Xu;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Iu||(Iu={}));class Ku{constructor(e){this.videoState=new k(Iu.STOPPED),this.maxSeekBackTime$=new t.ValueSubject(0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Iu.STOPPED&&(this.videoState.startTransitionTo(Iu.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(Iu.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===Iu.STOPPED)return this.videoState.startTransitionTo(Iu.READY),void this.prepare();if(a)this.prepare();else switch(e){case Iu.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Iu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Iu.PLAYING),this.playIfAllowed()));case Iu.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Iu.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Iu.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Iu.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=Fn(e.container),this.liveStreamClient=new Cu(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'WebRTCLiveProvider',message:'WebRTCLiveProvider internal logic error',thrown:t})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})}));const a=Gn(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.liveTime$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe((t=>{e.duration$.next(t===1/0?0:t)}))).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Iu.READY&&this.videoState.setState(Iu.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Iu.PAUSED)}),s)).add(a.playing$.subscribe((()=>{this.videoState.setState(Iu.PLAYING)}),s)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Bn(this.video,i.volume,a.volumeState$,s)).add(a.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe((s=>{switch(s.to){case Iu.STOPPED:e.position$.next(0),e.duration$.next(0),i.playbackState.setState(exports.PlaybackState.STOPPED);break;case Iu.READY:break;case Iu.PAUSED:i.playbackState.setState(exports.PlaybackState.PAUSED);break;case Iu.PLAYING:i.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(s.to)}}),s)).add(t.merge(i.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s))}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(ro(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=t,S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Iu.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(){po(this.video).then((t=>{t||(this.videoState.setState(Iu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}}class Zu{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 tl=qo(),el=(null===(Lu=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Lu?void 0:Lu.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),il=document.createElement('video'),sl={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Bu=null===(Ou=window.SourceBuffer)||void 0===Ou?void 0:Ou.prototype)||void 0===Bu?void 0:Bu.appendBuffer)),hls:Boolean((null===(Mu=il.canPlayType)||void 0===Mu?void 0:Mu.call(il,'application/x-mpegurl'))||(null===(Vu=il.canPlayType)||void 0===Vu?void 0:Vu.call(il,'vnd.apple.mpegURL'))),webrtc:Boolean(window.RTCPeerConnection)},al={mp4:Boolean(null===(Uu=il.canPlayType)||void 0===Uu?void 0:Uu.call(il,'video/mp4')),webm:Boolean(null===(Fu=il.canPlayType)||void 0===Fu?void 0:Fu.call(il,'video/webm'))},rl={h264:Boolean(null===(ju=null===(qu=window.MediaSource)||void 0===qu?void 0:qu.isTypeSupported)||void 0===ju?void 0:ju.call(qu,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Gu=null===(Hu=window.MediaSource)||void 0===Hu?void 0:Hu.isTypeSupported)||void 0===Gu?void 0:Gu.call(Hu,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(Qu=null===(Yu=window.MediaSource)||void 0===Yu?void 0:Yu.isTypeSupported)||void 0===Qu?void 0:Qu.call(Yu,'video/webm; codecs="vp9"')),aac:Boolean(null===(Wu=null===(zu=window.MediaSource)||void 0===zu?void 0:zu.isTypeSupported)||void 0===Wu?void 0:Wu.call(zu,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Xu=null===(Ju=window.MediaSource)||void 0===Ju?void 0:Ju.isTypeSupported)||void 0===Xu?void 0:Xu.call(Ju,'audio/webm; codecs="opus"'))},nl=(rl.h264||rl.h265)&&rl.aac,ol=!tl,ul=sl.hls&&al.mp4&&(el||tl),ll=Boolean(window.WebSocket);const dl=3e4,hl=18e4,cl=3,pl=100,ml={cacheDuration:12e4},fl={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Sl={maxPausedTime:3e4},bl={maxPausedTime:3e4};class vl{constructor(e){this.current$=new t.ValueSubject({type:void 0}),this.providerError$=new t.Subject,this.noAvailableProvidersError$=new t.Subject,this.providerOutput={position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),volume$:new t.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new t.ValueSubject(void 0),availableVideoTracks$:new t.ValueSubject([]),autoVideoTrackLimitingAvailable$:new t.ValueSubject(!1),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),error$:new t.Subject,willSeekEvent$:new t.Subject,seekedEvent$:new t.Subject,loopedEvent$:new t.Subject,endedEvent$:new t.Subject,firstBytesEvent$:new t.Subject,firstFrameEvent$:new t.Subject,canplay$:new t.Subject,isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),element$:new t.ValueSubject(void 0)},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:i}=this.params.tuning,s=i.length?[...e.screenFormatsPriority.filter((t=>!i.includes(t))),...e.screenFormatsPriority.filter((t=>i.includes(t)))]:e.screenFormatsPriority;this.screenFormatsIterator=new Zu(((e,i=!1)=>e.filter((e=>{switch(e){case exports.VideoFormat.DASH:return sl.mse&&al.mp4&&nl&&ol;case exports.VideoFormat.DASH_SEP:return sl.mse&&al.mp4&&nl;case exports.VideoFormat.DASH_WEBM:return sl.mse&&al.webm&&rl.vp9&&rl.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return sl.mse&&al.mp4&&nl;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return ul||i&&sl.mse&&al.mp4&&nl;case exports.VideoFormat.MPEG:return al.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return sl.webrtc&&ll&&rl.h264&&(al.mp4||al.webm);default:return t.assertNever(e)}})))(s.filter((i=>t.isNonNullable(e.sources[i]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Zu(e.chromecastFormatsPriority.filter((i=>t.isNonNullable(e.sources[i]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),i=this.chooseFormat(e);if(t.isNullable(i))return void this.handleNoFormatsError(e);let s;try{s=this.createProvider(e,i)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const e=this.current$.getValue().destination;t.assertNonNullable(e,'No current provider'),this.skipFormat(e),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!==d.None;this.params.desiredState.seekState.setState({state:d.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case n.SCREEN:return this.createScreenProvider(i);case n.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:a}=this.params,r=this.providerOutput,n={container:s,source:null,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const s=i[e];return t.assertNonNullable(s),new _o({...n,source:s,config:ml})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const s=i[e];return t.assertNonNullable(s),this.params.tuning.useDashJs?new ho({...n,source:s,format:e,config:bl}):new bu({...n,source:s})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const s=i[e];return t.assertNonNullable(s),ul||!this.params.tuning.useHlsJs?new Nu({...n,source:s}):new Tu({...n,source:s})}case exports.VideoFormat.HLS_LIVE:{const s=i[e];return t.assertNonNullable(s),new xu({...n,source:s,config:Sl})}case exports.VideoFormat.MPEG:{const s=i[e];return t.assertNonNullable(s),new Ru({...n,source:s})}case exports.VideoFormat.DASH_LIVE:{const s=i[e];return t.assertNonNullable(s),new wo({...n,source:s,config:fl})}case exports.VideoFormat.WEB_RTC_LIVE:{const n=i[e];return t.assertNonNullable(n),new Ku({container:s,source:n,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:a,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(o),new P({connection:o,meta:r,container:s,source:i,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?n.CHROMECAST:n.SCREEN}chooseFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case n.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.next();case n.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case n.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case n.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}initProviderErrorHandling(){let e=[],i=0;const s=new t.Subscription;var a;return s.add(t.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:dl,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(t.filter((({type:t})=>void 0!==t)))},new t.Observable((e=>{const i=new t.Subscription,s=a.desiredPlaybackState$.stateChangeStarted$.pipe(t.map((({from:t,to:e})=>`${t}-${e}`))),r=a.desiredPlaybackState$.stateChangeEnded$,n=a.providerChanged$,o=new t.Subject;let u=0,l='unknown';return i.add(s.subscribe((t=>{u&&window.clearTimeout(u),l=t,u=window.setTimeout((()=>o.next(t)),a.maxTransitionInterval)}))),i.add(r.subscribe((()=>{window.clearTimeout(u),l='provider change',u=0}))),i.add(n.subscribe((()=>{u&&(window.clearTimeout(u),u=window.setTimeout((()=>o.next(l)),a.maxTransitionInterval))}))),i.add(o.subscribe(e)),()=>{window.clearTimeout(u),i.unsubscribe()}}))).pipe(t.map((t=>({id:`ProviderHangup:${t}`,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),s.add(this.providerError$.pipe(t.throttle(pl,{leading:!1,trailing:!0})).subscribe((()=>{const s=Date.now();this.current$.getValue().destination===n.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):t.isNonNullable(e[i])&&s<e[i]+hl?(e=[],this.switchToNextProvider()):(e[i]=s,this.reinitProvider()),i=(i+1)%cl}))),s}}const gl=(t,e,i)=>i*e+(1-i)*t;class yl{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new eo(`raw_${s}`),this.smoothedSeries$=new eo(`smoothed_${s}`),this.reportedSeries$=new eo(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let i=0,s=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(i+=(this.pastMeasures[t]-this.smoothed)**2,s++);i/=s;const a=Math.sqrt(i),r=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=gl(this.slow,e,this.params.emaAlphaSlow),this.fast=gl(this.fast,e,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>r||this.smoothed<n||(t.isNullable(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 Tl;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Tl||(Tl={}));const El=new Map;let kl=Tl.RUNTIME;const wl=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(wl,'test'),localStorage.removeItem(wl),kl=Tl.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(wl),kl=Tl.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;kl=Tl.RUNTIME}}})();const Pl=(e,i)=>{switch(kl){case Tl.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Tl.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Tl.RUNTIME:return void El.set(e,i);default:t.assertNever(kl)}},$l=window.navigator.connection,Al=()=>{const e=null==$l?void 0:$l.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},xl=()=>{const e=null==$l?void 0:$l.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},Nl=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Rl{constructor(e){var i,s;this.subscription=new t.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Rl.load('one_video_throughput')||(e.useBrowserEstimation?Al():void 0)||5e3,r=null!==(s=null!==(i=Rl.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?xl():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(a),this.rtt$=new t.ValueSubject(r),this.rttAdjustedThroughput$=new t.ValueSubject(Nl(a,r,e.rttPenaltyRequestSize)),this.throughput=new yl({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new yl({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=Al();e&&this.throughput.next(e);const i=xl();t.isNonNullable(i)&&this.rtt.next(i)};$l&&'onchange'in $l&&this.subscription.add(t.fromEvent($l,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Pl('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Pl('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(t.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(t.map((({throughput:t,rtt:i})=>Nl(t,i,e.rttPenaltyRequestSize))),t.filter((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(e){let i=0,s=t.now();const a=new t.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:a.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}a.add(t.fromEvent(e,'loadend').subscribe((r=>{if(200===e.status){const e=r.loaded,a=t.now(),n=e-i,o=a-s;this.addRawSpeed(n,o,1)}this.concurrentDownloads.delete(e),a.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const a=t.now();let r=0,n=t.now();const o=t=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=async({done:l,value:d})=>{l?(this.addRawSpeed(s,t.now()-a,1),this.concurrentDownloads.delete(e)):d&&(s+=d.byteLength,r+=d.byteLength,r>=this.tuningConfig.streamMinSampleSize&&t.now()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,t.now()-n,this.concurrentDownloads.size),r=0,n=t.now()),await(null==i?void 0:i.read().then(u,o)))};this.concurrentDownloads.add(e),null==i||i.read().then(u,o)}addRawSpeed(t,e,i=1){if(Rl.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(e){var i;const s=(e=>{var i,s;switch(kl){case Tl.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case Tl.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case Tl.RUNTIME:return El.get(e);default:t.assertNever(kl)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const Dl={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 _l=({playbackState:e,seekState:i,playbackAbort$:s,looped$:a,position$:r})=>new t.Observable((n=>{let o;const u=e.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),l=e.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),h=i.stateChangeEnded$.pipe(t.filter((({to:t})=>{var i,s;return t.state===d.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===exports.PlaybackState.PLAYING}))),c=i.stateChangeEnded$.pipe(t.filter((({from:t,to:i})=>{var s,a;return t.state===d.Applying&&i.state===d.None&&(null!==(a=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==a?a:e.getState())===exports.PlaybackState.PLAYING}))),p=t.merge(u,c).pipe(t.map((()=>r.getValue())),t.filter(t.isNonNullable)),m=t.merge(t.merge(l,h,s),a).pipe(t.map((()=>r.getValue())),t.filter(t.isNonNullable));return(new t.Subscription).add(p.subscribe((t=>{o=t}))).add(m.subscribe((e=>{if(t.isNullable(o)||o===e)return;const i={from:o,to:e};o=void 0,n.next(i)})))})),Cl={[n.SCREEN]:{vod:[...ul?[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:[],exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,...ul?[]:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND],exports.VideoFormat.MPEG],live:ul?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE]},[n.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return t.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return t.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return t.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return t.ValueSubject}}),exports.Player=class{constructor(e={}){if(this.subscription=new t.Subscription,this.logger=new t.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new k(exports.PlaybackState.STOPPED),seekState:new k({state:d.None}),volume:new k({volume:1,muted:!1}),videoTrack:new k(void 0),autoVideoTrackSwitching:new k(!0),autoVideoTrackLimits:new k({}),isLooped:new k(!1),playbackRate:new k(1),externalTextTracks:new k([]),currentTextTrack:new k(void 0),textTrackCuesSettings:new k({})},this.info={playbackState$:new t.ValueSubject(exports.PlaybackState.STOPPED),position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),muted$:new t.ValueSubject(!1),volume$:new t.ValueSubject(1),availableQualities$:new t.ValueSubject([]),availableQualitiesFps$:new t.ValueSubject({}),currentQuality$:new t.ValueSubject(void 0),isAutoQualityEnabled$:new t.ValueSubject(!0),autoQualityLimitingAvailable$:new t.ValueSubject(!1),autoQualityLimits$:new t.ValueSubject({}),currentPlaybackRate$:new t.ValueSubject(1),currentBuffer$:new t.ValueSubject({start:0,end:0}),isBuffering$:new t.ValueSubject(!0),isStalled$:new t.ValueSubject(!1),isEnded$:new t.ValueSubject(!1),isLooped$:new t.ValueSubject(!1),isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),currentFormat$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),throughputEstimation$:new t.ValueSubject(void 0),rttEstimation$:new t.ValueSubject(void 0),videoBitrate$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),chromecastState$:new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new t.ValueSubject(void 0),intrinsicVideoSize$:new t.ValueSubject(void 0)},this.events={inited$:new t.Subject,started$:new t.Subject,startAttempt$:new t.Subject,willPause$:new t.Subject,willResume$:new t.Subject,willDestruct$:new t.Subject,watchCoverageRecord$:new t.Subject,watchCoverageLive$:new t.Subject,managedError$:new t.Subject,fatalError$:new t.Subject,ended$:new t.Subject,looped$:new t.Subject,seeked$:new t.Subject,willSeek$:new t.Subject,firstBytes$:new t.Subject,firstFrame$:new t.Subject,canplay$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:Zn},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Dl)){const s=Dl[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:null!=a?a:s}return e})(e),this.chromecastInitializer=new h({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Rl(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(e){var i,s;return this.config=e,this.domContainer=(e=>{const i='string'==typeof e.container?document.getElementById(e.container):e.container;return t.assertNonNullable(i,`Wrong container or containerId {${e.container}}`),i})(e),this.chromecastInitializer.contentId=null===(i=e.meta)||void 0===i?void 0:i.videoId,this.providerContainer=new vl({screenFormatsPriority:[...Cl[n.SCREEN].live,...Cl[n.SCREEN].vod],chromecastFormatsPriority:[...Cl[n.CHROMECAST].live,...Cl[n.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PAUSED&&t.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.STOPPED&&t.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:d.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()===exports.ChromecastState.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()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.availableVideoTracks$.getValue();i.length||(this.explicitInitialQuality=e);const s=i.find((t=>t.quality===e));return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setPlaybackRate(e){var i;t.assertNonNullable(this.providerContainer);const s=null===(i=this.providerContainer)||void 0===i?void 0:i.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){t.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(e))return this.info.position$.getValue();const i=this.desiredState.seekState.getState(),s=i.state===d.None?void 0:i.position;return t.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.autoQualityLimits$));const e=new t.Subscription;this.subscription.add(e),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING)),t.filter((()=>!this.isPlaybackStarted))).subscribe((()=>{this.initedAt=t.now(),this.events.inited$.next(),e.unsubscribe(),e.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING||t.to===exports.PlaybackState.PAUSED)),t.debounce(0),t.once()).subscribe((t=>{const e=t.to===exports.PlaybackState.PLAYING,i=this.info.muted$.getValue(),s=e?i?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===d.Requested?this.desiredState.seekState.setState({...t,state:d.Applying}):this.events.managedError$.next({id:`WillSeekIn${t.state}`,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===d.Applying&&(this.desiredState.seekState.setState({state:d.None}),this.events.seeked$.next())}))).add(e.current$.pipe(t.map((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(t.map((t=>t.destination)),t.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(t.map((t=>t.map((({quality:t})=>t)).sort(((t,e)=>E(t)?1:E(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(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(t.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(t.filterChanged()).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(t.map((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(t.map((t=>t.muted)),t.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.volume)),t.filterChanged()).subscribe(this.info.volume$)).add((({seekState:e,position$:i})=>t.merge(e.stateChangeEnded$.pipe(t.map((({to:t})=>{var e;return t.state===d.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>e.getState().state===d.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(t.merge(e.providerOutput.endedEvent$.pipe(t.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(t.mapTo(!1))).pipe(t.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(t.map((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(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let a=0;const r=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),a=i.getValue()||s.getValue();return t&&!a})),t.filterChanged());this.subscription.add(r.subscribe((t=>{t?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const n=new t.Subscription;this.subscription.add(n);const o=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),n.unsubscribe(),e){case!0:{const e=new t.ValueSubject(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),n.add(_l({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:e}).pipe(t.map((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(_l({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe(t.map((({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(t.map((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const i=new t.Subscription;this.subscription.add(i),this.subscription.add(e.current$.pipe(t.filterChanged(((t,e)=>t.provider===e.provider))).subscribe((()=>{i.unsubscribe(),i.add(e.providerOutput.availableVideoTracks$.pipe(t.filter((t=>t.length>0)),t.once()).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=ao(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(t.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(t.map((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput;t.assertNonNullable(this.providerContainer),t.assertNonNullable(i),Kn={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Xn=t})),this.providerContainer.current$.subscribe((({type:t})=>to('provider',t))),i.duration$.subscribe((t=>to('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>to('tracks',t))),this.events.fatalError$.subscribe(new eo('fatalError')),this.events.managedError$.subscribe(new eo('managedError')),i.position$.subscribe(new eo('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new eo('quality')),this.info.currentBuffer$.subscribe(new eo('buffer')),i.isBuffering$.subscribe(new eo('isBuffering'))].forEach((t=>this.subscription.add(t))),to('codecs',Object.keys(rl).filter((t=>rl[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.75-beta.0';
|
|
6
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2018.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce.js'));var a,r,o,n,l,u;exports.PlaybackState=void 0,(a=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',a.PLAYING='playing',a.PAUSED='paused',exports.VideoFormat=void 0,(r=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',r.DASH='DASH',r.DASH_SEP='DASH_SEP',r.DASH_SEP_VK='DASH_SEP',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_ONDEMAND_VK='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS',r.HLS_LIVE='HLS_LIVE',r.WEB_RTC_LIVE='WEB_RTC_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(o||(o={})),exports.ChromecastState=void 0,(n=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',n.AVAILABLE='AVAILABLE',n.CONNECTING='CONNECTING',n.CONNECTED='CONNECTED',exports.HttpConnectionType=void 0,(l=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',l.HTTP2='http2',l.QUIC='quic',function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(u||(u={}));class d{constructor(e){var i;this.connection$=new t.ValueSubject(void 0),this.castState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new t.Subject,this.realCastState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const s='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const a=t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast),r=Boolean(window.__onGCastApiAvailable);var o;a?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{delete window.__onGCastApiAvailable,t&&this.initializeCastApi()},r||(o='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',category:t.ErrorCategory.NETWORK,message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,a;null===(a=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===a||a.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,a;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(a=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===a?void 0:a.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 t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(h),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var r;const o=a===exports.ChromecastState.CONNECTED,n=t.isNonNullable(this.connection$.getValue());if(o&&!n){const a=s.getCurrentSession();t.assertNonNullable(a);const o=a.getCastDevice(),n=null===(r=a.getMediaSession())||void 0===r?void 0:r.media.contentId;(t.isNullable(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:a,castDevice:o}))}else!o&&n&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)})))}initializeCastApi(){var e;let i,s,a;try{i=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{i.setOptions({receiverApplicationId:null!==(e=this.params.receiverApplicationId)&&void 0!==e?e:s,autoJoinPolicy:a}),this.initListeners()}catch(e){this.errorEvent$.next({id:'ChromecastInitializer',category:t.ErrorCategory.EXTERNAL_API,message:'[initializeCastApi] failed',thrown:e})}}}const h=e=>{switch(e){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return t.assertNever(e)}};var c='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},p=function(t){try{return!!t()}catch(t){return!0}},m=!p((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),f=m,b=Function.prototype,S=b.bind,v=b.call,g=f&&S.bind(v,v),y=f?function(t){return t&&g(t)}:function(t){return t&&function(){return v.apply(t,arguments)}},T=y,E=T({}.toString),k=T(''.slice),w=function(t){return k(E(t),8,-1)},P=p,$=w,A=Object,x=y(''.split),N=P((function(){return!A('z').propertyIsEnumerable(0)}))?function(t){return'String'==$(t)?x(t,''):A(t)}:A,R=TypeError,D=function(t){if(null==t)throw R('Can\'t call method on '+t);return t},C=N,_=D,I=function(t){return C(_(t))},L={},O=function(t){return t&&t.Math==Math&&t},B=O('object'==typeof globalThis&&globalThis)||O('object'==typeof window&&window)||O('object'==typeof self&&self)||O('object'==typeof c&&c)||function(){return this}()||Function('return this')(),M=function(t){return'function'==typeof t},V=B,F=Object.defineProperty,U=function(t,e){try{F(V,t,{value:e,configurable:!0,writable:!0})}catch(i){V[t]=e}return e},q=B['__core-js_shared__']||U('__core-js_shared__',{}),j=M,H=q,G=y(Function.toString);j(H.inspectSource)||(H.inspectSource=function(t){return G(t)});var Y,Q,z=M,W=H.inspectSource,J=B.WeakMap,X=z(J)&&/native code/.test(W(J)),K=M,Z=function(t){return'object'==typeof t?null!==t:K(t)},tt=!p((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),et={},it=Z,st=B.document,at=it(st)&&it(st.createElement),rt=function(t){return at?st.createElement(t):{}},ot=rt,nt=!tt&&!p((function(){return 7!=Object.defineProperty(ot('div'),'a',{get:function(){return 7}}).a})),lt=tt&&p((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ut=Z,dt=String,ht=TypeError,ct=function(t){if(ut(t))return t;throw ht(dt(t)+' is not an object')},pt=m,mt=Function.prototype.call,ft=pt?mt.bind(mt):function(){return mt.apply(mt,arguments)},bt={},St=bt,vt=B,gt=M,yt=function(t){return gt(t)?t:void 0},Tt=function(t,e){return arguments.length<2?yt(St[t])||yt(vt[t]):St[t]&&St[t][e]||vt[t]&&vt[t][e]},Et=y({}.isPrototypeOf),kt=B,wt=Tt('navigator','userAgent')||'',Pt=kt.process,$t=kt.Deno,At=Pt&&Pt.versions||$t&&$t.version,xt=At&&At.v8;xt&&(Q=(Y=xt.split('.'))[0]>0&&Y[0]<4?1:+(Y[0]+Y[1])),!Q&&wt&&(!(Y=wt.match(/Edge\/(\d+)/))||Y[1]>=74)&&(Y=wt.match(/Chrome\/(\d+)/))&&(Q=+Y[1]);var Nt=Q,Rt=p,Dt=!!Object.getOwnPropertySymbols&&!Rt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Nt&&Nt<41})),Ct=Dt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,_t=Tt,It=M,Lt=Et,Ot=Object,Bt=Ct?function(t){return'symbol'==typeof t}:function(t){var e=_t('Symbol');return It(e)&&Lt(e.prototype,Ot(t))},Mt=String,Vt=function(t){try{return Mt(t)}catch(t){return'Object'}},Ft=M,Ut=Vt,qt=TypeError,jt=function(t){if(Ft(t))return t;throw qt(Ut(t)+' is not a function')},Ht=jt,Gt=function(t,e){var i=t[e];return null==i?void 0:Ht(i)},Yt=ft,Qt=M,zt=Z,Wt=TypeError,Jt={exports:{}},Xt=q;(Jt.exports=function(t,e){return Xt[t]||(Xt[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.24.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.24.1/LICENSE',source:'https://github.com/zloirock/core-js'});var Kt=D,Zt=Object,te=function(t){return Zt(Kt(t))},ee=te,ie=y({}.hasOwnProperty),se=Object.hasOwn||function(t,e){return ie(ee(t),e)},ae=y,re=0,oe=Math.random(),ne=ae(1..toString),le=function(t){return'Symbol('+(void 0===t?'':t)+')_'+ne(++re+oe,36)},ue=B,de=Jt.exports,he=se,ce=le,pe=Dt,me=Ct,fe=de('wks'),be=ue.Symbol,Se=be&&be.for,ve=me?be:be&&be.withoutSetter||ce,ge=function(t){if(!he(fe,t)||!pe&&'string'!=typeof fe[t]){var e='Symbol.'+t;pe&&he(be,t)?fe[t]=be[t]:fe[t]=me&&Se?Se(e):ve(e)}return fe[t]},ye=ft,Te=Z,Ee=Bt,ke=Gt,we=function(t,e){var i,s;if('string'===e&&Qt(i=t.toString)&&!zt(s=Yt(i,t)))return s;if(Qt(i=t.valueOf)&&!zt(s=Yt(i,t)))return s;if('string'!==e&&Qt(i=t.toString)&&!zt(s=Yt(i,t)))return s;throw Wt('Can\'t convert object to primitive value')},Pe=TypeError,$e=ge('toPrimitive'),Ae=function(t,e){if(!Te(t)||Ee(t))return t;var i,s=ke(t,$e);if(s){if(void 0===e&&(e='default'),i=ye(s,t,e),!Te(i)||Ee(i))return i;throw Pe('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),we(t,e)},xe=Bt,Ne=function(t){var e=Ae(t,'string');return xe(e)?e:e+''},Re=tt,De=nt,Ce=lt,_e=ct,Ie=Ne,Le=TypeError,Oe=Object.defineProperty,Be=Object.getOwnPropertyDescriptor;et.f=Re?Ce?function(t,e,i){if(_e(t),e=Ie(e),_e(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Be(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Oe(t,e,i)}:Oe:function(t,e,i){if(_e(t),e=Ie(e),_e(i),De)try{return Oe(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Le('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Me,Ve,Fe,Ue=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},qe=et,je=Ue,He=tt?function(t,e,i){return qe.f(t,e,je(1,i))}:function(t,e,i){return t[e]=i,t},Ge=Jt.exports,Ye=le,Qe=Ge('keys'),ze=function(t){return Qe[t]||(Qe[t]=Ye(t))},We={},Je=X,Xe=B,Ke=y,Ze=Z,ti=He,ei=se,ii=q,si=ze,ai=We,ri=Xe.TypeError,oi=Xe.WeakMap;if(Je||ii.state){var ni=ii.state||(ii.state=new oi),li=Ke(ni.get),ui=Ke(ni.has),di=Ke(ni.set);Me=function(t,e){if(ui(ni,t))throw new ri('Object already initialized');return e.facade=t,di(ni,t,e),e},Ve=function(t){return li(ni,t)||{}},Fe=function(t){return ui(ni,t)}}else{var hi=si('state');ai[hi]=!0,Me=function(t,e){if(ei(t,hi))throw new ri('Object already initialized');return e.facade=t,ti(t,hi,e),e},Ve=function(t){return ei(t,hi)?t[hi]:{}},Fe=function(t){return ei(t,hi)}}var ci={set:Me,get:Ve,has:Fe,enforce:function(t){return Fe(t)?Ve(t):Me(t,{})},getterFor:function(t){return function(e){var i;if(!Ze(e)||(i=Ve(e)).type!==t)throw ri('Incompatible receiver, '+t+' required');return i}}},pi=m,mi=Function.prototype,fi=mi.apply,bi=mi.call,Si='object'==typeof Reflect&&Reflect.apply||(pi?bi.bind(fi):function(){return bi.apply(fi,arguments)}),vi={},gi={},yi={}.propertyIsEnumerable,Ti=Object.getOwnPropertyDescriptor,Ei=Ti&&!yi.call({1:2},1);gi.f=Ei?function(t){var e=Ti(this,t);return!!e&&e.enumerable}:yi;var ki=tt,wi=ft,Pi=gi,$i=Ue,Ai=I,xi=Ne,Ni=se,Ri=nt,Di=Object.getOwnPropertyDescriptor;vi.f=ki?Di:function(t,e){if(t=Ai(t),e=xi(e),Ri)try{return Di(t,e)}catch(t){}if(Ni(t,e))return $i(!wi(Pi.f,t,e),t[e])};var Ci=p,_i=M,Ii=/#|\.prototype\./,Li=function(t,e){var i=Bi[Oi(t)];return i==Vi||i!=Mi&&(_i(e)?Ci(e):!!e)},Oi=Li.normalize=function(t){return String(t).replace(Ii,'.').toLowerCase()},Bi=Li.data={},Mi=Li.NATIVE='N',Vi=Li.POLYFILL='P',Fi=Li,Ui=jt,qi=m,ji=y(y.bind),Hi=function(t,e){return Ui(t),void 0===e?t:qi?ji(t,e):function(){return t.apply(e,arguments)}},Gi=B,Yi=Si,Qi=y,zi=M,Wi=vi.f,Ji=Fi,Xi=bt,Ki=Hi,Zi=He,ts=se,es=function(t){var e=function(i,s,a){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,a)}return Yi(t,this,arguments)};return e.prototype=t.prototype,e},is=function(t,e){var i,s,a,r,o,n,l,u,d=t.target,h=t.global,c=t.stat,p=t.proto,m=h?Gi:c?Gi[d]:(Gi[d]||{}).prototype,f=h?Xi:Xi[d]||Zi(Xi,d,{})[d],b=f.prototype;for(a in e)i=!Ji(h?a:d+(c?'.':'#')+a,t.forced)&&m&&ts(m,a),o=f[a],i&&(n=t.dontCallGetSet?(u=Wi(m,a))&&u.value:m[a]),r=i&&n?n:e[a],i&&typeof o==typeof r||(l=t.bind&&i?Ki(r,Gi):t.wrap&&i?es(r):p&&zi(r)?Qi(r):r,(t.sham||r&&r.sham||o&&o.sham)&&Zi(l,'sham',!0),Zi(f,a,l),p&&(ts(Xi,s=d+'Prototype')||Zi(Xi,s,{}),Zi(Xi[s],a,r),t.real&&b&&!b[a]&&Zi(b,a,r)))},ss=tt,as=se,rs=Function.prototype,os=ss&&Object.getOwnPropertyDescriptor,ns=as(rs,'name'),ls={EXISTS:ns,PROPER:ns&&'something'===function(){}.name,CONFIGURABLE:ns&&(!ss||ss&&os(rs,'name').configurable)},us={},ds=Math.ceil,hs=Math.floor,cs=Math.trunc||function(t){var e=+t;return(e>0?hs:ds)(e)},ps=function(t){var e=+t;return e!=e||0===e?0:cs(e)},ms=ps,fs=Math.max,bs=Math.min,Ss=ps,vs=Math.min,gs=function(t){return t>0?vs(Ss(t),9007199254740991):0},ys=function(t){return gs(t.length)},Ts=I,Es=function(t,e){var i=ms(t);return i<0?fs(i+e,0):bs(i,e)},ks=ys,ws=function(t){return function(e,i,s){var a,r=Ts(e),o=ks(r),n=Es(s,o);if(t&&i!=i){for(;o>n;)if((a=r[n++])!=a)return!0}else for(;o>n;n++)if((t||n in r)&&r[n]===i)return t||n||0;return!t&&-1}},Ps={includes:ws(!0),indexOf:ws(!1)},$s=se,As=I,xs=Ps.indexOf,Ns=We,Rs=y([].push),Ds=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Cs=function(t,e){var i,s=As(t),a=0,r=[];for(i in s)!$s(Ns,i)&&$s(s,i)&&Rs(r,i);for(;e.length>a;)$s(s,i=e[a++])&&(~xs(r,i)||Rs(r,i));return r},_s=Ds,Is=Object.keys||function(t){return Cs(t,_s)},Ls=tt,Os=lt,Bs=et,Ms=ct,Vs=I,Fs=Is;us.f=Ls&&!Os?Object.defineProperties:function(t,e){Ms(t);for(var i,s=Vs(e),a=Fs(e),r=a.length,o=0;r>o;)Bs.f(t,i=a[o++],s[i]);return t};var Us,qs=Tt('document','documentElement'),js=ct,Hs=us,Gs=Ds,Ys=We,Qs=qs,zs=rt,Ws=ze('IE_PROTO'),Js=function(){},Xs=function(t){return'<script>'+t+'<\/script>'},Ks=function(t){t.write(Xs('')),t.close();var e=t.parentWindow.Object;return t=null,e},Zs=function(){try{Us=new ActiveXObject('htmlfile')}catch(t){}var t,e;Zs='undefined'!=typeof document?document.domain&&Us?Ks(Us):((e=zs('iframe')).style.display='none',Qs.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Xs('document.F=Object')),t.close(),t.F):Ks(Us);for(var i=Gs.length;i--;)delete Zs.prototype[Gs[i]];return Zs()};Ys[Ws]=!0;var ta,ea,ia,sa=Object.create||function(t,e){var i;return null!==t?(Js.prototype=js(t),i=new Js,Js.prototype=null,i[Ws]=t):i=Zs(),void 0===e?i:Hs.f(i,e)},aa=!p((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ra=se,oa=M,na=te,la=aa,ua=ze('IE_PROTO'),da=Object,ha=da.prototype,ca=la?da.getPrototypeOf:function(t){var e=na(t);if(ra(e,ua))return e[ua];var i=e.constructor;return oa(i)&&e instanceof i?i.prototype:e instanceof da?ha:null},pa=He,ma=function(t,e,i,s){return s&&s.enumerable?t[e]=i:pa(t,e,i),t},fa=p,ba=M,Sa=sa,va=ca,ga=ma,ya=ge('iterator'),Ta=!1;[].keys&&('next'in(ia=[].keys())?(ea=va(va(ia)))!==Object.prototype&&(ta=ea):Ta=!0);var Ea=null==ta||fa((function(){var t={};return ta[ya].call(t)!==t}));ba((ta=Ea?{}:Sa(ta))[ya])||ga(ta,ya,(function(){return this}));var ka={IteratorPrototype:ta,BUGGY_SAFARI_ITERATORS:Ta},wa={};wa[ge('toStringTag')]='z';var Pa='[object z]'===String(wa),$a=Pa,Aa=M,xa=w,Na=ge('toStringTag'),Ra=Object,Da='Arguments'==xa(function(){return arguments}()),Ca=$a?xa:function(t){var e,i,s;return void 0===t?'Undefined':null===t?'Null':'string'==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=Ra(t),Na))?i:Da?xa(e):'Object'==(s=xa(e))&&Aa(e.callee)?'Arguments':s},_a=Ca,Ia=Pa?{}.toString:function(){return'[object '+_a(this)+']'},La=Pa,Oa=et.f,Ba=He,Ma=se,Va=Ia,Fa=ge('toStringTag'),Ua=function(t,e,i,s){if(t){var a=i?t:t.prototype;Ma(a,Fa)||Oa(a,Fa,{configurable:!0,value:e}),s&&!La&&Ba(a,'toString',Va)}},qa=ka.IteratorPrototype,ja=sa,Ha=Ue,Ga=Ua,Ya=L,Qa=function(){return this},za=(TypeError,y);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=za(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Wa=is,Ja=ft,Xa=function(t,e,i,s){var a=e+' Iterator';return t.prototype=ja(qa,{next:Ha(+!s,i)}),Ga(t,a,!1,!0),Ya[a]=Qa,t},Ka=ca,Za=Ua,tr=ma,er=L,ir=ls.PROPER,sr=ka.BUGGY_SAFARI_ITERATORS,ar=ge('iterator'),rr=function(){return this},or=I,nr=L,lr=ci;et.f;var ur=function(t,e,i,s,a,r,o){Xa(i,e,s);var n,l,u,d=function(t){if(t===a&&f)return f;if(!sr&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},h=e+' Iterator',c=!1,p=t.prototype,m=p[ar]||p['@@iterator']||a&&p[a],f=!sr&&m||d(a),b='Array'==e&&p.entries||m;if(b&&(n=Ka(b.call(new t)))!==Object.prototype&&n.next&&(Za(n,h,!0,!0),er[h]=rr),ir&&'values'==a&&m&&'values'!==m.name&&(c=!0,f=function(){return Ja(m,this)}),a)if(l={values:d('values'),keys:r?f:d('keys'),entries:d('entries')},o)for(u in l)(sr||c||!(u in p))&&tr(p,u,l[u]);else Wa({target:e,proto:!0,forced:sr||c},l);return o&&p[ar]!==f&&tr(p,ar,f,{name:a}),er[e]=f,l},dr=lr.set,hr=lr.getterFor('Array Iterator');ur(Array,'Array',(function(t,e){dr(this,{type:'Array Iterator',target:or(t),index:0,kind:e})}),(function(){var t=hr(this),e=t.target,i=t.kind,s=t.index++;return!e||s>=e.length?(t.target=void 0,{value:void 0,done:!0}):'keys'==i?{value:s,done:!1}:'values'==i?{value:e[s],done:!1}:{value:[s,e[s]],done:!1}}),'values'),nr.Arguments=nr.Array;var cr=L,pr=ge('iterator'),mr=Array.prototype,fr=Ca,br=Gt,Sr=L,vr=ge('iterator'),gr=function(t){if(null!=t)return br(t,vr)||br(t,'@@iterator')||Sr[fr(t)]},yr=ft,Tr=jt,Er=ct,kr=Vt,wr=gr,Pr=TypeError,$r=ft,Ar=ct,xr=Gt,Nr=Hi,Rr=ft,Dr=ct,Cr=Vt,_r=function(t){return void 0!==t&&(cr.Array===t||mr[pr]===t)},Ir=ys,Lr=Et,Or=function(t,e){var i=arguments.length<2?wr(t):e;if(Tr(i))return Er(yr(i,t));throw Pr(kr(t)+' is not iterable')},Br=gr,Mr=function(t,e,i){var s,a;Ar(t);try{if(!(s=xr(t,'return'))){if('throw'===e)throw i;return i}s=$r(s,t)}catch(t){a=!0,s=t}if('throw'===e)throw i;if(a)throw s;return Ar(s),i},Vr=TypeError,Fr=function(t,e){this.stopped=t,this.result=e},Ur=Fr.prototype,qr=Ne,jr=et,Hr=Ue,Gr=function(t,e,i){var s,a,r,o,n,l,u,d=i&&i.that,h=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=Nr(e,d),b=function(t){return s&&Mr(s,'normal',t),new Fr(!0,t)},S=function(t){return h?(Dr(t),m?f(t[0],t[1],b):f(t[0],t[1])):m?f(t,b):f(t)};if(c)s=t.iterator;else if(p)s=t;else{if(!(a=Br(t)))throw Vr(Cr(t)+' is not iterable');if(_r(a)){for(r=0,o=Ir(t);o>r;r++)if((n=S(t[r]))&&Lr(Ur,n))return n;return new Fr(!1)}s=Or(t,a)}for(l=c?t.next:s.next;!(u=Rr(l,s)).done;){try{n=S(u.value)}catch(t){Mr(s,'throw',t)}if('object'==typeof n&&n&&Lr(Ur,n))return n}return new Fr(!1)},Yr=function(t,e,i){var s=qr(e);s in t?jr.f(t,s,Hr(0,i)):t[s]=i};is({target:'Object',stat:!0},{fromEntries:function(t){var e={};return Gr(t,(function(t,i){Yr(e,t,i)}),{AS_ENTRIES:!0}),e}});var Qr=bt.Object.fromEntries,zr={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Wr=B,Jr=Ca,Xr=He,Kr=L,Zr=ge('toStringTag');for(var to in zr){var eo=Wr[to],io=eo&&eo.prototype;io&&Jr(io)!==Zr&&Xr(io,Zr,to),Kr[to]=Kr.Array}var so,ao=Qr;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(so||(so={}));var ro,oo=(e,i=0,s=so.OFFSET_P)=>{switch(s){case so.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case so.PLAYBACK_SHIFT:{if(0===i)return e;const t=new URL(e);return t.searchParams.append('playback_shift',i.toFixed(0)),t.toString()}default:t.assertNever(s)}return e},no=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};exports.VideoQuality=void 0,(ro=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',ro.Q_144P='144p',ro.Q_240P='240p',ro.Q_360P='360p',ro.Q_480P='480p',ro.Q_720P='720p',ro.Q_1080P='1080p',ro.Q_1440P='1440p',ro.Q_2160P='2160p',ro.Q_4320P='4320p';const lo={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},uo=(t,e)=>lo[t].height>lo[e].height,ho=(t,e)=>lo[t].height<lo[e].height,co=Object.keys(lo).sort(((t,e)=>ho(t,e)?-1:1)),po=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return co.find((t=>{const e=lo[t];return e.width>=s&&e.height>=i}))},mo=t=>t===exports.VideoQuality.INVARIANT;class fo{constructor(e){this.transitionStarted$=new t.Subject,this.transitionEnded$=new t.Subject,this.transitionUpdated$=new t.Subject,this.forceChanged$=new t.Subject,this.stateChangeStarted$=t.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=t.merge(this.transitionEnded$,this.forceChanged$),this.state=e}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(e){const i=this.transition,s=this.state;s===e||t.isNonNullable(i)&&i.to===e||(this.state=e,i?(this.transition={from:i.from,to:e,canceledTransition:i},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var bo;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(bo||(bo={}));class So{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new fo(bo.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)if((null==a?void 0:a.to)===exports.PlaybackState.PAUSED||r.state!==u.Requested||e===bo.STOPPED)switch(s){case exports.PlaybackState.PLAYING:switch(e){case bo.PLAYING:break;case bo.PAUSED:case bo.READY:this.videoState.startTransitionTo(bo.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case bo.STOPPED:this.videoState.startTransitionTo(bo.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case bo.PLAYING:this.videoState.startTransitionTo(bo.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case bo.PAUSED:break;case bo.READY:this.videoState.startTransitionTo(bo.PAUSED),this.videoState.setState(bo.PAUSED);break;case bo.STOPPED:this.videoState.startTransitionTo(bo.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}else this.seek(r.position)}else e!==bo.STOPPED&&(this.videoState.startTransitionTo(bo.STOPPED),this.stop())},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next((e=>{switch(e){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(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 t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(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===u.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,a=this.params.output.isBuffering$.getValue(),r=s===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:t.assertNever(s)}})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));i(t.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(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(bo.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(bo.PLAYING),no(this.params.desiredState.playbackState,exports.PlaybackState.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:u.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==bo.PAUSED&&t!==bo.PLAYING||(this.videoState.setState(bo.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==bo.PLAYING&&t!==bo.PAUSED||(this.videoState.setState(bo.PLAYING),no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===bo.READY&&this.videoState.setState(bo.READY)}handleRemoteStop(){this.videoState.getState()!==bo.STOPPED&&this.videoState.setState(bo.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),a={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};a.volume===s.volume&&a.muted==a.muted||this.params.output.volume$.next(a)}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(e){var i;const s=this.params.source;let a,r,o;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const n=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:ho(t,e)?1:-1))[0];t.assertNonNullable(n);const l=i[n];t.assertNonNullable(l),a=l,r='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),a=oo(i.url),r='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const e='Unsupported format for Chromecast',i=new Error(e);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',category:t.ErrorCategory.VIDEO_PIPELINE,message:e,thrown:i}),i}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}const n=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:a,r);n.contentUrl=a,n.streamType=o,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:l,subtitle:u}=this.params.meta;return t.isNonNullable(l)&&(n.metadata.title=l),t.isNonNullable(u)&&(n.metadata.subtitle=u),n}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===u.Applying||i.state===u.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(e){const i=this.params.connection.session.loadMedia(e),s=new Promise(((e,i)=>{this.loadMediaTimeoutSubscription.add(t.timeout(7e3).subscribe((()=>i('timeout(7000)'))))}));Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===u.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(e=>{const i=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:i}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',category:t.ErrorCategory.VIDEO_PIPELINE,message:i,thrown:e})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}class vo{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 go extends vo{constructor(){super(),this.listeners||vo.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 yo{constructor(){Object.defineProperty(this,'signal',{value:new go,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 To(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&&(yo.prototype[Symbol.toStringTag]='AbortController',go.prototype[Symbol.toStringTag]='AbortSignal');const Eo=To({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ko=Eo?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(!To({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 o=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,o(t,e)])}return o(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wo=Eo?ko.fetch:window.fetch;Eo?ko.Request:window.Request;const Po=Eo?yo:window.AbortController,$o=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Ao{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=$o(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){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),a=this.activeRequests.get(i.url);s&&a&&a.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,i){const s=i.map($o),a=s[0][0];let r=s[0][1];for(let t=1;t<s.length&&r<this.params.minDataSize;t++){const e=s[t][1];e-a<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===a?Math.max(r,a+this.params.minInitSize):Math.max(r,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append('bytes',`${a}-${r}`);const n=o.toString(),l=new Po,u=l.signal,d={url:e,from:a,to:r,loaded:0,data:null,abortController:l};u.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const h=e=>{var i,s;throw null===(s=(i=this.params).onError)||void 0===s||s.call(i,{id:'BigRequestParsing',category:t.ErrorCategory.PARSER,message:'Error parsing response data',thrown:e}),e};return wo(n,{signal:u}).then((t=>{var e,i,s;if(d.response=t,!t.ok||!t.body)return void this.onBigRequestError(d);const[o,n]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,n);const l=o.getReader(),u=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10)||r-a+1;d.data=new ArrayBuffer(u);const c=new Uint8Array(d.data),p=async({done:t,value:e})=>{t?this.onBigRequestProgress(d):e&&(c.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),await(null==l?void 0:l.read().then(p,Ao.suppressStreamErrors).catch(h)))};null==l||l.read().then(p,Ao.suppressStreamErrors).catch(h)}),Ao.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a,response:r}){var o,n,l,u,d,h,c,p;if(!this.activeRequests.has(t)||!a)return;const m=null!==(o=this.dashJsRequestQueue.get(t))&&void 0!==o?o:[];for(const o of m){const{request:m}=o,[f,b]=$o(m),S=f>=e&&b<=e+s,v=e>=f&&e+s<b,g=a.slice(f-e,Math.min(b-e+1,s));if((S||v)&&(m.requestStartDate=null!==(n=m.requestStartDate)&&void 0!==n?n:new Date,m.firstByteDate=null!==(l=m.firstByteDate)&&void 0!==l?l:new Date,m.bytesLoaded=g.byteLength,m.bytesTotal=i-e),S){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==o))),null===(d=o.success)||void 0===d||d.call(o,g,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(h=this.dashMetrics)||void 0===h||h.addHttpRequest(m,t,null!==(c=null==r?void 0:r.status)&&void 0!==c?c:200,e,[])}else v&&(null===(p=o.progress)||void 0===p||p.call(o,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:i,to:s},a){var r,o,n,l;if(null===(o=(r=this.params).onError)||void 0===o||o.call(r,{id:'BigRequest',category:t.ErrorCategory.NETWORK,message:'Download error',thrown:a}),!this.activeRequests.has(e))return;const u=null!==(n=this.dashJsRequestQueue.get(e))&&void 0!==n?n:[];for(const t of u){const[e,r]=$o(t.request);(e>=i&&e<s||r>i&&r<=s)&&(null===(l=null==t?void 0:t.error)||void 0===l||l.call(t,t.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:t,from:e,to:i}){var s,a;if(!this.activeRequests.has(t))return;const r=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of r){const[s,r]=$o(t.request);(s>=e&&s<i||r>e&&r<=i)&&(null===(a=null==t?void 0:t.abort)||void 0===a||a.call(t,t.request))}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class xo{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(xo.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;xo.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const No=(t,e)=>{const i=new Ao(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 xo(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var Ro=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&(null==e||e())}}}),!0)},Do=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject,a=new t.ValueSubject(void 0),r=new t.ValueSubject(void 0);let o=NaN,n=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,l=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const l=e.onload,u=e.progress;e.onload=function(...e){return(e=>{var s,o,n,l,u;const d=ao(e.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in d||'x-playback-duration-millis'in d){const a=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),r=parseInt(null!==(o=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==o?o:'',10),l=null!==(n=null!=r?r:1e3*a)&&void 0!==n?n:NaN;t.isNonNullable(l)&&!isNaN(l)&&i.next(l)}const h=null!==(l=d['x-delivery-type'])&&void 0!==l?l:exports.HttpConnectionType.HTTP1,c=null!==(u={1:!0,0:!1}[d['x-reused']])&&void 0!==u?u:void 0;a.next(h),r.next(c)})(this),l(...e)},e.progress=function(...t){return this.readyState>=2&&!n&&(n=!0,s.next(Date.now()-o)),u(...t)},o=Date.now(),n=!1}return l(e)}}}),!0),{playbackDuration$:i,ping$:s,connectionReused$:r,connectionType$:a}},Co=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},_o=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 Io=(e,i,s,{equal:a=((t,e)=>t===e),changed$:r,onError:o}={})=>{const n=e.getState(),l=i(),u=t.isNullable(r),d=new t.Subscription;return r&&d.add(r.subscribe((t=>{const i=e.getState();a(t,i)&&e.setState(t)}),o)),a(l,n)||(s(n),u&&e.setState(n)),d.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),u&&e.setState(t.to)}),o)),d},Lo=(e,i,s)=>Io(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),Oo=(e,i,s,a)=>Io(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:s,onError:a}),Bo=(e,i,s,a)=>Io(i,(()=>e.playbackRate),(i=>{t.isNonNullable(i)&&(e.playbackRate=i)}),{changed$:s,onError:a}),Mo=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class Vo{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const a=e=>{this.error$.next({id:'TextTracksManager',category:t.ErrorCategory.WTF,message:'Generic HtmlVideoTextTrackManager error',thrown:e})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Io(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(Io(i.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(Io(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);const a=t=>{var e,i,s,r,o;const n=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;n&&n.length&&(this.applyCueSettings(null!==(r=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==r?r:null),null===(o=t.target)||void 0===o||o.removeEventListener('cuechange',a))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',a)}))),this.subscription.add(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter(Vo.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(e){t.assertNonNullable(this.video);for(const i of this.htmlTextTracksAsArray(!0))t.isNonNullable(e)&&Mo(i,e)?i.mode='showing':i.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(e){t.assertNonNullable(this.video);const i=document.createElement('track');i.setAttribute('src',e.url),i.setAttribute('id',e.id),e.label&&i.setAttribute('label',e.label),e.language&&i.setAttribute('srclang',e.language),this.externalTracks.set(e.id,e),this.video.appendChild(i)}detach(e){t.assertNonNullable(this.video);const i=Array.prototype.find.call(this.video.getElementsByTagName('track'),(t=>t.getAttribute('id')===e));i&&this.video.removeChild(i),this.externalTracks.delete(e)}}var Fo=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 Uo{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}var qo=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};class jo{constructor(t){this._buffer=[],this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:a})=>{const r=s>=t&&s<e,o=a>=t&&a<e;r&&o||(r?i(e,a):o?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var Ho=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const o=t.start(r),n=t.end(r);if(o<=e&&e<=n){if(s=o,a=n,!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 Go=e=>{const i=i=>t.fromEvent(e,i).pipe(t.mapTo(void 0)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((t=>'ended'===t.type?e.readyState<2:e.readyState<3)),t.filterChanged()),a=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>Ho(e.buffered,e.currentTime)))),r=qo()?t.combine({play:i('play').pipe(t.once()),playing:i('playing')}).pipe(t.mapTo(void 0)):i('playing'),o=t.fromEvent(e,'volumechange').pipe(t.map((()=>({muted:e.muted,volume:e.volume})))),n=t.fromEvent(e,'ratechange').pipe(t.map((()=>e.playbackRate))),l=t.fromEvent(e,'error').pipe(t.filter((()=>Boolean(e.error||e.played.length))),t.map((()=>{var i;const s=e.error;return{id:s?`MediaError#${s.code}`:'HtmlVideoError',category:t.ErrorCategory.VIDEO_PIPELINE,message:s?s.message:'Error event from HTML video element',thrown:null!==(i=e.error)&&void 0!==i?i:void 0}}))),u=t.fromEvent(e,'timeupdate').pipe(t.map((()=>e.currentTime))),d=new t.Subject;let h;return u.subscribe((i=>{e.loop&&t.isNonNullable(h)&&t.isNonNullable(i)&&h>=e.duration-.3&&i<=.3&&d.next(h),h=i})),{playing$:r,pause$:i('pause').pipe(t.filter((()=>!e.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:d,error$:l,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:u,durationChange$:t.fromEvent(e,'durationchange').pipe(t.map((()=>e.duration))),isBuffering$:s,currentBuffer$:a,volumeState$:o,playbackRateState$:n}},Yo=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var Qo=te,zo=ys,Wo=ps;is({target:'Array',proto:!0},{at:function(t){var e=Qo(this),i=zo(e),s=Wo(t),a=s>=0?s:i+s;return a<0||a>=i?void 0:e[a]}});var Jo=Tt('Array','at');let Xo=!1,Ko={};const Zo=t=>{t(Ko)},tn=(t,e)=>{var i;Xo&&(Ko.meta=null!==(i=Ko.meta)&&void 0!==i?i:{},Ko.meta[t]=e)};class en{constructor(t){this.name=t}next(t){var e,i;if(!Xo)return;Ko.series=null!==(e=Ko.series)&&void 0!==e?e:{};const s=null!==(i=Ko.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Ko.series[this.name]=s}}const sn=new en('best_bitrate');class an{constructor(){this.history={}}recordSelection(e){this.history[e.id]=t.now()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const rn=(e,{container:i,throughput:s,tuning:a,limits:r,reserve:o=0,forwardBufferHealth:n,playbackRate:l,current:u,history:d})=>{var h,c,p,m;const f=a.usePixelRatio&&null!==(h=window.devicePixelRatio)&&void 0!==h?h:1,b=a.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*f*a.containerSizeFactor,height:i.height*f*a.containerSizeFactor},S=b&&po(b),v=a.considerPlaybackRate&&t.isNonNullable(l)?l:1,g=e.filter((t=>!mo(t.quality))).sort(((t,e)=>uo(t.quality,e.quality)?-1:1)),y=null===(c=Jo(g,-1))||void 0===c?void 0:c.quality,T=null===(p=Jo(g,0))||void 0===p?void 0:p.quality,E=t.isNullable(r)||t.isNonNullable(r.min)&&t.isNonNullable(r.max)&&ho(r.max,r.min)||t.isNonNullable(r.min)&&T&&uo(r.min,T)||t.isNonNullable(r.max)&&y&&ho(r.max,y),k=v*(w=null!=n?n:.5,P=a.bitrateFactorAtEmptyBuffer,$=a.bitrateFactorAtFullBuffer,(P-$)*Math.pow(2,-10*w)+$);var w,P,$;const A=g.filter((e=>{const i=!S||ho(e.quality,S),l=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s-o>=e.bitrate*k,d=a.lazyQualitySwitch&&t.isNonNullable(a.minBufferToSwitchUp)&&u&&!mo(u.quality)&&(null!=n?n:0)<a.minBufferToSwitchUp&&uo(e.quality,u.quality),h=E||(t.isNullable(r.max)||(c=e.quality,p=r.max,lo[c].height<=lo[p].height))&&(t.isNullable(r.min)||((t,e)=>lo[t].height>=lo[e].height)(e.quality,r.min));var c,p;return i&&l&&!d&&h}))[0];A&&A.bitrate&&sn.next(A.bitrate);const x=null!==(m=null!=A?A:g[Math.ceil((g.length-1)/2)])&&void 0!==m?m:e[0],N=x&&d&&d.history[x.id]&&t.now()-d.history[x.id]<=a.trackCooldown&&(!d.last||x.id!==d.last.id);if((null==x?void 0:x.id)&&d&&!N&&d.recordSelection(x),N&&(null==d?void 0:d.last)){const t=d.last;return null==d||d.recordSwitch(t),t}return null==d||d.recordSwitch(x),x};var on=t=>new URL(t).hostname;const nn=(e,i=300)=>new t.Observable((a=>{const{width:r,height:o}=e.getBoundingClientRect();if(a.next({width:r,height:o}),!window.ResizeObserver)return;const n=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,r;i.contentBoxSize&&i.contentBoxSize[0]?(r=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,r=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(r)&&a.next({width:s,height:r})}),i));return n.observe(e),()=>n.disconnect()})),ln={};var un;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(un||(un={}));const dn=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class hn{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(un.DOWNLOADING_LIB),this.textTracksManager=new Vo,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t.ValueSubject(void 0),this.maxSeekBackTime$=new t.ValueSubject(1/0),this.availableFrom$=new t.ValueSubject(void 0),this.elementSize$=new t.ValueSubject(void 0),this.liveOffset=new Uo,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&e!==un.DOWNLOADING_LIB&&e!==un.STREAM_INITIALIZED)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===u.Requested&&e!==un.STOPPED&&i!==exports.PlaybackState.STOPPED&&(r?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case exports.PlaybackState.STOPPED:switch(e){case un.STOPPED:break;case un.PLAYING:case un.PAUSED:case un.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case un.PLAYING:break;case un.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case un.READY:this.play();break;case un.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case un.PLAYING:this.pause(),this.liveOffset.pause();break;case un.PAUSED:break;case un.READY:this.videoState.setState(un.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case un.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Fo(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const s=i=>{var s;e||this.params.output.error$.next({id:'timeout'===i?'DashJSTimedOut':'DashJSLoadingError',category:t.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${null===(s=null==i?void 0:i.toString)||void 0===s?void 0:s.call(i)}`,thrown:i}),e=!0},a=window.setTimeout((()=>s('timeout')),5e3);Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((t=>{e||(ln.MediaPlayer=t.MediaPlayer,ln.Debug=t.Debug,this.init())}),s).finally((()=>{window.clearTimeout(a),e=!0}))}init(){t.assertNonNullable(ln.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(ln.Debug,'dashjs not loaded'),this.player=ln.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?Yo(t.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=No(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&&_o(this.player),Ro(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:Co})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(un.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'DashIFProvider',category:t.ErrorCategory.WTF,message:'DashIFProvider internal logic error',thrown:i})},a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(nn(this.video),this.elementSize$),a(dn(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),a(dn(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const r=dn(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));r.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===un.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(Io(i.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(Io(i.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:s})),a(dn(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),a(dn(this.player,'fragmentLoadingStarted'),(({mediaType:t,request:{url:i}})=>{var s,a;const r=this.player.getDashMetrics(),o=r.getLatestFragmentRequestHeaderValueByID(t,'X-Reused'),n=null!==(s=r.getLatestFragmentRequestHeaderValueByID(t,'X-Delivery-Type'))&&void 0!==s?s:exports.HttpConnectionType.HTTP1,l=null!==(a={1:!0,0:!1}[o])&&void 0!==a?a:void 0;this.params.output.httpConnectionType$.next(n),this.params.output.httpConnectionReused$.next(l),e.hostname$.next(on(i))})),a(dn(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),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=po(t),s=t.bitrate/1e3,o={width:t.width,height:t.height},n=this.frameRatesByFrameHeight[t.height];if(i){const l={id:e,quality:i,bitrate:s,size:o,fps:n};this.videoTracks.push({track:l,bitrateInfo:t}),t.qualityIndex===a&&(r=l)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&e.currentVideoTrack$.next(r),this.videoState.setState(un.STREAM_INITIALIZED),this.videoState.startTransitionTo(un.READY)})),a(dn(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),a(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=rn(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const o=dn(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));a(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:o}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(o.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),a(dn(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),a(dn(this.player,'playbackEnded'),e.endedEvent$),a(dn(this.player,'playbackProgress').pipe(t.map((()=>Ho(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),a(dn(this.player,'playbackPlaying'),(()=>{this.videoState.setState(un.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)})),a(dn(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(un.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(dn(this.player,'playbackPaused'),(()=>{this.videoState.setState(un.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)})),a(dn(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===un.READY&&this.videoState.setState(un.READY)})),a(this.isLive$,e.isLive$),a(nn(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:n,ping$:l,connectionType$:u,connectionReused$:d}=Do(this.player);a(u,this.params.output.httpConnectionType$),a(d,this.params.output.httpConnectionReused$),a(n,this.maxSeekBackTime$),a(l.pipe(t.once()),e.firstBytesEvent$),a(dn(this.player,'canPlay'),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(o.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(dn(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{this.subscription.add(dn(this.player,'playbackPlaying').pipe(t.once(),t.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))}),s)),this.subscription.add(Lo(this.video,i.isLooped,s));const{volumeState$:h,looped$:c,playbackRateState$:p}=Go(this.video);this.subscription.add(Oo(this.video,i.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(c.subscribe(e.loopedEvent$)),this.subscription.add(Bo(this.video,i.playbackRate,p,s))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(un.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(un.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=oo(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,so.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(un.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(un.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var cn=t=>{switch(t){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}},pn=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 mn(){return t.now()}function fn(t){return mn()-t}function bn(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 Sn(e,i,s,a){const r=window.XMLHttpRequest;let o,n,l,u,d,h=!1,c=0,p=!1,m='arraybuffer',f=7e3,b=2e3,S=()=>{if(h)return;t.assertNonNullable(u);const e=fn(u);let i;if(e<b)return i=b-e,void setTimeout(S,i);b*=2,b>f&&(b=f),n&&n.abort(),n=new r,g()};const v=()=>{if(!h){if(--c>=0)return S(),void(a&&a());h=!0,d&&d(),s&&s()}},g=()=>{u=mn(),n=new r,n.open('get',e);let s,a=0,c=0;const f=()=>(t.assertNonNullable(u),Math.max(u,Math.max(s||0,c||0)));if(o&&n.addEventListener('progress',(t=>{const e=mn();o.updateChunk&&t.loaded>a&&(o.updateChunk(f(),t.loaded-a),a=t.loaded,s=e)})),l&&(n.timeout=l,n.addEventListener('timeout',(()=>v()))),n.addEventListener('load',(()=>{if(h)return;t.assertNonNullable(n);const e=n.status;if(e>=200&&e<300){if(n.response.byteLength&&o){const t=n.response.byteLength-a;t&&o.updateChunk&&o.updateChunk(f(),t)}d&&d(),n&&i(n.response)}else v()})),n.addEventListener('error',(()=>{v()})),p){const e=()=>{t.assertNonNullable(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(c=mn(),n.removeEventListener('readystatechange',e))};n.addEventListener('readystatechange',e)}return n.responseType=m,n.send(),y},y={withBitrateReporting:t=>(o=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(c=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(b=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(l=t,y),withFinally:t=>(d=t,y),send:g,abort:()=>{n&&(n.abort(),n=void 0),h=!0,d&&d()}};return y}class vn{constructor(t){this.intervals=[],this.currentRate=0,this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const o=t.bytes*a/r;s+=o,t.start=e,t.bytes-=o}}}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 gn{constructor(t,e,i,s,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=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=mn(),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=Sn(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=mn()-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=mn()}_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=mn();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 yn{constructor(t){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=t,this.chunkRateEstimator=new vn(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=bn(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=bn(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',(()=>{var i;Boolean(t.error)&&!this.destroyed&&(e(`Video element error: ${null===(i=t.error)||void 0===i?void 0:i.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 e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>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 gn(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:a}=this.params;let r=!1,o=null,n=null,l=null,u=null,d=!1;const h=()=>{const t=r&&(!d||d===this.rep);return t||i('Not running!'),t},c=(t,e,i)=>{l&&l.abort(),l=Sn(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{l=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==n||n.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{n=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=mn()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const a=this.bufferStates[i];t=Math.min(t,a.buf),a.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,m(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else m(1)},S=e=>{let s;const r=()=>s&&s.start?s.start.length:0,o=t=>s.start[t]/1e3,n=t=>s.dur[t]/1e3,l=t=>s.fragIndex+t,d=(t,e)=>({chunkIdx:l(t),startTS:o(t),dur:n(t),discontinuity:e}),c=()=>{let t=0;if(s&&s.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,i=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=e;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=s.dur.length-1;for(;r>=0&&(a-=s.dur[r],!(a<=0));--r);t=Math.min(r,s.dur.length-1-i),t=Math.max(t,0)}return d(t,!0)},p=(t,e,i)=>{u&&u.abort(),u=Sn(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(i,n)=>{p(e,(e=>{if(!h())return;s=e;const l=Boolean(s.lowLatency);l!==this.lowLatency&&f(l);let u=0;for(let t=0;t<s.dur.length;++t)u+=s.dur[t];u>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/s.dur.length)),a({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=r();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(o(t)>e)return d(t);return c()}})(n))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=r(),a=t?t.chunkIdx+1:0,o=a-s.fragIndex;if(!(e<=0)){if(!t||o<0||o-e>10)return i(`Resync: offset=${o} bChunks=${e} chunk=`+JSON.stringify(t)),c();if(!(o>=e))return d(a-s.fragIndex,!1)}}}},v=()=>{r=!1,n&&n.abort(),l&&l.abort(),u&&u.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:i=>{const{videoElement:s,logger:a}=this.params;let n,l,d,m,f,g,y,T=S(e.jidxUrl),E=0;const k=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=mn(),s=Math.min(1e4,e-i);E=i;const a=()=>{u||h()&&T.seek((()=>{h()&&(E=mn(),w(),k())}))};s>0?f=window.setTimeout((()=>{this.paused?k():a()}),s):a()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(d);if(i){if(d&&i.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?k():(v(),this._initPlayerWith(e)));x(i)}else k()},P=(t,e)=>{if(!h()||!this.sourceBuffer)return;let i,r,o;const n=i=>{window.setTimeout((()=>{h()&&P(t,e)}),i)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const l=mn(),u=s.currentTime;!this.paused&&s.buffered.length>1&&g===u&&l-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,y=l);const d=this._getBufferSizeSec();if(d>30)a(`Buffered ${d} seconds; delaying appendBuffer`),n(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:l,buf:d}),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;a('QuotaExceededError; delaying appendBuffer'),o=this.sourceBuffer.buffered.length,0!==o&&(i=this.sourceBuffer.buffered.start(0),r=u,r-i>4&&this.sourceBuffer.remove(i,r-3)),n(1e3)}}},$=()=>{l&&n&&(a([`Appending chunk, sz=${l.byteLength}:`,JSON.stringify(d)]),P(l,(function(){l=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{h()&&p(A(t),((e,i)=>{if(h()){if(i/=1e3,l=e,d=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{h()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},R=t=>{h()&&(e.cachedHeader=t,P(t,(()=>{n=!0,$()})))};r=!0,T.seek((e=>{h()&&(E=mn(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(d=e,w())):k())}),i),e.cachedHeader?R(e.cachedHeader):c(e.headerUrl,R,(()=>this._handleNetworkError()))},stop:v,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),t.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_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=mn();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,o=!0;const n=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(o&&t>a&&fn(r)<3e4)return;i(t)}o=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&n(),i},notifySwitch:t=>{const e=mn();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=Sn(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;pn(e).then((e=>{e||null==t||t()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return(null==t?void 0:t.length)?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var Tn;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Tn||(Tn={}));const En=[Tn.PAUSED,Tn.PLAYING,Tn.READY],kn=[Tn.PAUSED,Tn.PLAYING,Tn.READY];class wn{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(Tn.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new Vo,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new Uo,this._dashCb=e=>{var i,s,a,r;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:t.ErrorCategory.WTF,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,r=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),a=null!==(s=cn(e.name))&&void 0!==s?s:po(e.video),o=e.bitrate/1e3,n={...e.video};if(!a)continue;const l={id:t,quality:a,bitrate:o,size:n};r.push({track:l,representation:e})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),(null===(a=this.videoState.getTransition())||void 0===a?void 0:a.to)===Tn.MANIFEST_READY&&this.videoState.setState(Tn.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(r=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===r?void 0:r.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(o)};`}),a!==exports.PlaybackState.STOPPED){if(!s){if(kn.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&o.state===u.Requested&&En.includes(i))this.seek(o.position-this.liveOffset.getTotalPausedTime());else switch(i){case Tn.STOPPED:return this.videoState.startTransitionTo(Tn.MANIFEST_READY),void this.dash.attachSource(oo(this.params.source.url));case Tn.MANIFEST_READY:this.videoState.startTransitionTo(Tn.READY),this.prepare();break;case Tn.READY:return void(a===exports.PlaybackState.PAUSED?this.videoState.setState(Tn.PAUSED):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Tn.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Tn.PAUSED)}))));case Tn.PLAYING:return void(a===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(Tn.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Tn.PAUSED:return void(a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Tn.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(Tn.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return t.assertNever(i)}}}else i!==Tn.STOPPED&&(this.videoState.startTransitionTo(Tn.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Tn.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=i=>{e.output.error$.next({id:'DashLiveProvider',category:t.ErrorCategory.WTF,message:'DashLiveProvider internal logic error',thrown:i})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Fo(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Go(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Tn.READY&&this.videoState.setState(Tn.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(Tn.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===u.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Tn.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(t.combine({zeroTime:this.zeroTime$.pipe(t.filter(t.isNonNullable)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)).add(Lo(this.video,this.params.desiredState.isLooped,i)).add(Oo(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(Bo(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,i)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&lo[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case Tn.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case Tn.MANIFEST_READY:case Tn.READY:break;case Tn.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case Tn.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(e.to)}}),i)).add(t.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new yn({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var e,i,s,a,r,o;const n=this.representations$.getValue(),l=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),u=null!==(a=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==a?a:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!u&&t.isNonNullable(l)?l:null===(r=rn(n.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))||void 0===r?void 0:r.id,h=null===(o=n.find((({track:t})=>t.id===d)))||void 0===o?void 0:o.representation;t.assertNonNullable(h,'Representations missing'),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(d),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var i;const s=null===(i=this.representations$.getValue().find((({track:t})=>t.id===e)))||void 0===i?void 0:i.representation;t.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}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(oo(this.params.source.url,i))}}var Pn=t=>{var e,i;const s=t.get('X-Delivery-Type'),a=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===a?void 0:null!==(i={1:!0,0:!1}[a])&&void 0!==i?i:void 0}},$n=(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 An{constructor(t,e=[],i,s,a,r){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=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 e=!1;this._xhr.onreadystatechange=()=>{var i,s,a,r,o,n,l,u;if(t.assertNonNullable(this._xhr),(null===(i=this._xhr)||void 0===i?void 0:i.status)>=400)return null===(s=this._errorCb)||void 0===s||s.call(this,`Http${null===(a=this._xhr)||void 0===a?void 0:a.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!e){e=!0;const t=ao(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(o=this._headersCb)||void 0===o||o.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(l=this._progressCb)||void 0===l||l.call(this,this._xhr.response))}catch(t){throw null===(u=this._errorCb)||void 0===u||u.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class xn{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,o){this.abort((()=>{let n=0;const l=Date.now();let u=0,d=0,h=0;const c=t=>{s(xn._str2ua(t.substr(n))),n=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=Co(p)),this._lastXhr=new An(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(t);const e=Date.now()-l;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==a||a()}),(t=>{if(t.length-n>o&&c(t),0===d)return void(d=Date.now());h=t.length-u;const e=Date.now()-d;h>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:h,duration:e,speed:8*h/(e/1e3)}),h=0,u=t.length,d=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=xn._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class Nn{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=Co(i)),new An(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=[],o=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,n,l,u,d,h,c,p,m,f,b,S,v,g,y,T,E,k,w;const P=t.getElementsByTagName('SegmentBase')[0],$=P&&a(P,'indexRange').split('-'),A=P&&P.getElementsByTagName('Initialization')[0],x=A&&a(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const a=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,r=(i?i+'/':'')+(null===(d=null===(u=null===(l=null===(n=t.getElementsByTagName('BaseURL'))||void 0===n?void 0:n[0])||void 0===l?void 0:l.childNodes)||void 0===u?void 0:u[0])||void 0===d?void 0:d.data),c=null!==(h=e.getAttribute('lang'))&&void 0!==h?h:void 0;r&&o.push({id:a,url:r,language:c})}return}const N=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const C=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=C?Yo(C):void 0,r.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(b=t.attributes.getNamedItem('height'))||void 0===b?void 0:b.value),bandwidth:N,baseURL:R,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(v=null===(S=t.attributes.getNamedItem('codecs'))||void 0===S?void 0:S.value)&&void 0!==v?v:void 0,mimeType:null!==(y=null===(g=t.attributes.getNamedItem('mimeType'))||void 0===g?void 0:g.value)&&void 0!==y?y:void 0,fps:D,bufferSize:.1*N/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==(w=null===(k=t.attributes.getNamedItem('id'))||void 0===k?void 0:k.value)&&void 0!==w?w:void 0})})),r.length?(this._representations=r,o.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 o=a.getUint32(s,!1),n=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const l=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<l;e+=1){const e=n+(2147483647&a.getUint32(s,!1)),i=o+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:o/r,toTime:i/r,fromOffset:n,toOffset:e-1}),n=e,o=i}const u=t.refs[t.refs.length-1];u.toTime-u.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,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)))}},o=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}o()}),250)},n=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new xn({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||o(),i.removeEventListener('sourceopen',n),i.removeEventListener('webkitsourceopen',n)};i.addEventListener('sourceopen',n,!1),i.addEventListener('webkitsourceopen',n,!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 e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const a=i[e];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Rn;!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'}(Rn||(Rn={}));const Dn=[Rn.PAUSED,Rn.PLAYING];class Cn{constructor(e){this.videoState=new fo(Rn.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new Vo,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},this.handleManifestReady=t=>{var e,i,s;const a=[];for(const r of t){const t=null!==(i=null!==(e=r.name)&&void 0!==e?e:r.id)&&void 0!==i?i:r.height.toString(10),o=null!==(s=r.name&&cn(r.name))&&void 0!==s?s:po(r),n=r.bandwidth/1e3,l={width:r.width,height:r.height},u=r.fps;if(!o)continue;const d={id:t,quality:o,bitrate:n,size:l,fps:u};a.push({track:d,representation:r})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),this.videoState.setState(Rn.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)switch((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&r.state===u.Requested&&Dn.includes(e)&&this.seek(r.position,r.forcePrecise),e){case Rn.STOPPED:return this.videoState.startTransitionTo(Rn.MANIFEST_LOADED),void this.prepare();case Rn.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Rn.INITIAL_REPRESENTATION_SELECTED);case Rn.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Rn.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Rn.METADATA_LOADED:return this.videoState.startTransitionTo(Rn.READY),void this.dash.updateRefsForCurrentTime();case Rn.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Rn.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Rn.PLAYING),this.playIfAllowed()));case Rn.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Rn.PAUSED),this.video.pause()):(null==a?void 0:a.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Rn.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Rn.PLAYING),this.playIfAllowed()):(null==a?void 0:a.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Rn.STOPPED&&(this.videoState.startTransitionTo(Rn.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(Rn.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Fo(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new jo(this.video),this.dash=new Nn({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:(e,i,s)=>{this.log({message:`[DashLite error], ${e}`}),this.dashLiteEvents.error$.next({id:e,message:i,thrown:s,category:t.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'DashProvider',category:t.ErrorCategory.WTF,message:'DashProvider internal logic error',thrown:i})},a=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},r=Go(this.video),o=(t,e)=>this.subscription.add(t.subscribe(e,s));o(r.timeUpdate$,e.position$),o(r.durationChange$,e.duration$),o(r.ended$,e.endedEvent$),o(r.looped$,e.loopedEvent$),o(r.error$,e.error$),o(r.isBuffering$,e.isBuffering$),o(r.playing$,e.firstFrameEvent$),o(r.canplay$,e.canplay$),this.subscription.add(r.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekState.getState().state!==u.Applying)&&(this.videoState.getState()===Rn.PLAYING||this.videoState.getState()===Rn.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Lo(this.video,i.isLooped,s)),this.subscription.add(Oo(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Bo(this.video,i.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),o(nn(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Rn.READY&&this.videoState.setState(Rn.READY)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Rn.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Rn.PLAYING),no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Rn.METADATA_LOADED)}),s)).add(r.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:e,message:i,thrown:s})=>({id:`DashLite_${e}`,category:t.ErrorCategory.WTF,message:i,thrown:s})))).subscribe(this.params.output.error$)).add(t.merge(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$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i,s;const r=this.currentRepresentation$.getValue(),o=this.representations$.getValue(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),d=this.elementSize$.getValue(),h=a();let c;if(n&&this.params.desiredState.autoVideoTrackSwitching.setState(n.to),!h&&t.isNonNullable(l))c=l;else{const t=$n(this.video.buffered,1e3*this.video.currentTime),s=h?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(t/s,1);c=null===(i=rn(o.map((({track:t})=>t)),{container:d,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:null===(e=o.find((({representation:t})=>t===r)))||void 0===e?void 0:e.track}))||void 0===i?void 0:i.id}return t.isNonNullable(c)?null===(s=o.find((({track:t})=>t.id===c)))||void 0===s?void 0:s.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===Rn.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(Rn.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?t.height<=e.height:t===e))).subscribe((t=>{const e=$n(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!a())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(on(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Pn(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once(),t.mapTo(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(t.filter(t.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case'url':this.dash.attachSource(e.url);break;case'raw':this.dash.attachManifest(e.raw);break;default:return t.assertNever(e)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(Rn.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var _n,In,Ln,On,Bn;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(_n||(_n={})),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'}(In||(In={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(Ln||(Ln={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(On||(On={})),function(t){t.MP4='mp4',t.WEBM='webm'}(Bn||(Bn={}));var Mn=(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 Vn='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;var Fn,Un;let qn=!1;try{qn=qo()&&parseInt(null!==(Un=null===(Fn=navigator.userAgent.match(/Version\/(\d+)/))||void 0===Fn?void 0:Fn[1])&&void 0!==Un?Un:'',10)<16}catch(t){console.error(t)}class jn{constructor(e){this.bufferFull$=new t.Subject,this.error$=new t.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var e;try{if(this.currentTask){const t=null===(e=this.currentTask.signal)||void 0===e?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:'BufferTaskQueueUnknown',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Buffer appending or removal failed',thrown:e})}},this.buffer=e,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=qn&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const i=this.queue.shift();if(!i)return;if(null===(e=i.signal)||void 0===e?void 0:e.aborted)return i.callback(!1),void this.pull();this.currentTask=i;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(e){e instanceof DOMException&&'QuotaExceededError'===e.name&&'append'===s?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&'InvalidStateError'===e.name&&'remove'===s||this.error$.next({id:`BufferTaskQueue:${s}`,category:t.ErrorCategory.VIDEO_PIPELINE,message:'Buffer operation failed',thrown:e}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(e){const{operation:i}=e;switch(i){case'append':this.buffer.appendBuffer(e.data);break;case'remove':this.buffer.remove(e.from/1e3,e.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(e.init);break;default:t.assertNever(i)}}}var Hn,Gn=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'}(Hn||(Hn={}));class Yn{constructor({throughputEstimator:e,requestQuic:i}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new Po,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=Co(e));const i=yield wo(e,{signal:this.abortAllController.signal}).catch(Qn);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetch=t.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:i=Hn.HEADER,range:s,onProgress:a,priority:r='auto',signal:o,measureThroughput:n=!0}={}){var l,u,d,h;let c=e;const p=new Headers;if(s)switch(i){case Hn.HEADER:p.append('Range',`${s.from}-${s.to}`);break;case Hn.PARAM:{const t=new URL(c,location.href);t.searchParams.append('bytes',`${s.from}-${s.to}`),c=t.toString();break}default:t.assertNever(i)}this.requestQuic&&(c=Co(c));let m=this.abortAllController.signal;if(o){const e=new Po;if(this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(o,'abort')).subscribe((()=>{try{e.abort()}catch(t){Qn(t)}}))),this.abortAllController.signal.aborted||o.aborted)try{e.abort()}catch(t){Qn(t)}m=e.signal}const f=t.now(),b=yield wo(c,{priority:r,headers:p,signal:m}).catch(Qn),S=t.now();if(null===(l=this.throughputEstimator)||void 0===l||l.addRawRtt(S-f),!b)return null;if(!b.ok||!b.body)return Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const v=parseInt(null!==(u=b.headers.get('Content-Length'))&&void 0!==u?u:'',10)||s&&s.to-s.from+1||NaN;if(!v){const e=yield b.arrayBuffer();return null===(d=this.throughputEstimator)||void 0===d||d.addRawSpeed(e.byteLength,t.now()-S),null==a||a(new DataView(e),e.byteLength),e}if(!a&&!n)return b.arrayBuffer();const[g,y]=b.body.tee(),T=g.getReader();n&&(null===(h=this.throughputEstimator)||void 0===h||h.trackStream(y));let E=0;const k=new ArrayBuffer(v),w=new Uint8Array(k),P=new DataView(k);let $=!1;const A=t=>{$=!0,Qn(t)},x=t.abortable(m,async function*({done:e,value:i}){0===E&&this.lastRequestFirstBytes$.next(t.now()-f),m.aborted||(e?null==a||a(P,E):i&&(w.set(i,E),E+=i.byteLength,null==a||a(P,E),yield null==T?void 0:T.read().then(x,A)))}.bind(this));return yield null==T?void 0:T.read().then(x,A),$?null:k}.bind(this)),this.fetchByteRangeRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e,i){if(t.type!==Ln.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,o,n=s,l=a,u=!1;t.indexRange&&(r=t.indexRange.from,o=t.indexRange.to,u=a+1===r,u&&(n=Math.min(r,s),l=Math.max(o,a))),n=Math.min(n,0);const d=yield this.fetch(t.url,{rangeMethod:Hn.PARAM,range:{from:n,to:l},priority:i,measureThroughput:!1});if(!d)return null;const h=new DataView(d,s-n,a-n+1);if(!e.validateData(h))throw new Error('Invalid media file');const c=e.parseInit(h);let p;if(u&&void 0!==r&&void 0!==o)p=new DataView(d,r-n,o-r+1);else{const s=e.getIndexRange(c);if(s){const e=yield this.fetch(t.url,{rangeMethod:Hn.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,c);return{dataView:new DataView(d),segments:m}}.bind(this)),this.fetchTemplateRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e){if(t.type!==Ln.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:On.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=Pn(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,i,s='auto'){var a,r;const{type:o}=e;switch(o){case Ln.BYTE_RANGE:return null!==(a=await this.fetchByteRangeRepresentation(e,i,s))&&void 0!==a?a:null;case Ln.TEMPLATE:return null!==(r=await this.fetchTemplateRepresentation(e,s))&&void 0!==r?r:null;default:t.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qn=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},zn=new TextDecoder('ascii'),Wn=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=zn.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)}},Jn={validateData:t=>'ftyp'===zn.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Wn(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(),o=a(),n=a(),l=4294967295&a();let u=o/r*1e3,d=t.byteOffset+t.byteLength+n;for(let t=0;t<l;t++){const t=a(),e=t>>>31,s=t<<1>>>1,o=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const n=o/r*1e3;i.push({status:On.NONE,time:{from:u,to:u+n},byte:{from:d,to:d+s-1}}),u+=n,d+=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=Wn(a);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var Xn,Kn;!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'}(Xn||(Xn={})),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'}(Kn||(Kn={}));const Zn={[Xn.EBML]:{type:Kn.Master},[Xn.EBMLVersion]:{type:Kn.UnsignedInteger},[Xn.EBMLReadVersion]:{type:Kn.UnsignedInteger},[Xn.EBMLMaxIDLength]:{type:Kn.UnsignedInteger},[Xn.EBMLMaxSizeLength]:{type:Kn.UnsignedInteger},[Xn.DocType]:{type:Kn.String},[Xn.DocTypeVersion]:{type:Kn.UnsignedInteger},[Xn.DocTypeReadVersion]:{type:Kn.UnsignedInteger},[Xn.Void]:{type:Kn.Binary},[Xn.Segment]:{type:Kn.Master},[Xn.SeekHead]:{type:Kn.Master},[Xn.Seek]:{type:Kn.Master},[Xn.SeekID]:{type:Kn.Binary},[Xn.SeekPosition]:{type:Kn.UnsignedInteger},[Xn.Info]:{type:Kn.Master},[Xn.TimestampScale]:{type:Kn.UnsignedInteger},[Xn.Duration]:{type:Kn.Float},[Xn.Tracks]:{type:Kn.Master},[Xn.Chapters]:{type:Kn.Master},[Xn.Cluster]:{type:Kn.Master},[Xn.Timestamp]:{type:Kn.UnsignedInteger},[Xn.SilentTracks]:{type:Kn.Master},[Xn.SilentTrackNumber]:{type:Kn.UnsignedInteger},[Xn.Position]:{type:Kn.UnsignedInteger},[Xn.PrevSize]:{type:Kn.UnsignedInteger},[Xn.SimpleBlock]:{type:Kn.Binary},[Xn.BlockGroup]:{type:Kn.Master},[Xn.EncryptedBlock]:{type:Kn.Binary},[Xn.Attachments]:{type:Kn.Master},[Xn.Tags]:{type:Kn.Master},[Xn.Cues]:{type:Kn.Master},[Xn.CuePoint]:{type:Kn.Master},[Xn.CueTime]:{type:Kn.UnsignedInteger},[Xn.CueTrackPositions]:{type:Kn.Master},[Xn.CueTrack]:{type:Kn.UnsignedInteger},[Xn.CueClusterPosition]:{type:Kn.UnsignedInteger},[Xn.CueRelativePosition]:{type:Kn.UnsignedInteger},[Xn.CueDuration]:{type:Kn.UnsignedInteger},[Xn.CueBlockNumber]:{type:Kn.UnsignedInteger},[Xn.CueCodecState]:{type:Kn.UnsignedInteger},[Xn.CueReference]:{type:Kn.Master},[Xn.CueRefTime]:{type:Kn.UnsignedInteger}},tl=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=el(t,i),a=s in Zn,r=a?Zn[s].type:Kn.Binary,o=t.getUint8(i);let n=0;128&o?n=1:64&o?n=2:32&o?n=3:16&o?n=4:8&o?n=5:4&o?n=6:2&o?n=7:1&o&&(n=8);const l=new DataView(t.buffer,t.byteOffset+i+1,n-1),u=((o&255>>n)<<8*(n-1))+el(l),d=i+n;let h;return h=d+u>t.byteLength?new DataView(t.buffer,t.byteOffset+d):new DataView(t.buffer,t.byteOffset+d,u),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:d,tagSize:d+u,value:h,valueSize:u}},el=(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},il=(e,i)=>{switch(i){case Kn.SignedInteger:return e.getInt8(0);case Kn.UnsignedInteger:return el(e);case Kn.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case Kn.String:return new TextDecoder('ascii').decode(e);case Kn.UTF8:return new TextDecoder('utf-8').decode(e);case Kn.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case Kn.Master:case Kn.Binary:return e;default:t.assertNever(i)}},sl=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=tl(s);if(!e(a))return;a.type===Kn.Master&&sl(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},al=[Xn.Info,Xn.SeekHead,Xn.Tracks,Xn.Chapters,Xn.Cluster,Xn.Cues,Xn.Attachments,Xn.Tags],rl=[Xn.Timestamp,Xn.SilentTracks,Xn.SilentTrackNumber,Xn.Position,Xn.PrevSize,Xn.SimpleBlock,Xn.BlockGroup,Xn.EncryptedBlock],ol={validateData:t=>{if(t.getUint32(0)!==Xn.EBML)return!1;let e,i,s;const a=tl(t);return sl(a.value,(({tag:t,type:a,value:r})=>(t===Xn.EBMLReadVersion?e=il(r,a):t===Xn.DocType?i=il(r,a):t===Xn.DocTypeReadVersion&&(s=il(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,a,r,o,n,l=!1,u=!1,d=!1;return sl(e,(({tag:t,type:e,value:h,valueSize:c})=>{if(t===Xn.SeekID){const t=il(h,e);n=el(t)}else t!==Xn.SeekPosition&&(n=void 0);return t===Xn.Segment?(i=h.byteOffset,s=h.byteOffset+c):t===Xn.Info?l=!0:t===Xn.SeekHead?u=!0:t===Xn.TimestampScale?a=il(h,e):t===Xn.Duration?r=il(h,e):t===Xn.SeekPosition&&n===Xn.Cues?o=il(h,e):l&&u&&al.includes(t)&&(d=!0),!d})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(r,'Failed to parse webm Segment duration'),a=null!=a?a:1e6,{segmentStart:Math.round(i/1e9*a*1e3),segmentEnd:Math.round(s/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:o}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,a=!1;const r=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),o=[];let n;return sl(e,(({tag:t,type:e,value:i})=>{switch(t){case Xn.Cues:s=!0;break;case Xn.CuePoint:n&&r(n)&&o.push(n),n={};break;case Xn.CueTime:n&&(n.time=il(i,e));break;case Xn.CueTrackPositions:break;case Xn.CueClusterPosition:n&&(n.position=il(i,e));break;default:s&&al.includes(t)&&(a=!0)}return!(s&&a)})),n&&r(n)&&o.push(n),o.map(((t,e)=>{const{time:s,position:a}=t,r=o[e+1];return{status:On.NONE,time:{from:s,to:r?r.time:i.segmentDuration},byte:{from:i.segmentStart+a,to:r?i.segmentStart+r.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{sl(t,(s=>s.tag===Xn.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!rl.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[Xn.SimpleBlock,Xn.BlockGroup,Xn.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class nl{constructor(e,i,s,a,{fetcher:r,tuning:o,getCurrentPosition:n}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Po,this.destroyAbortController=new Po,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=t.abortable(this.destroyAbortController.signal,async function*(e){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.sourceBufferTaskQueue=new jn(this.sourceBuffer),this.subscription.add(t.fromEvent(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(e=>this.error$.next({id:'SegmentEjection',category:t.ErrorCategory.WTF,message:'Error when trying to clear segments ejected by browser',thrown:e})))),this.subscription.add(t.fromEvent(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',category:t.ErrorCategory.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,Gn(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield this.loadInit(i,'high',!0);const s=this.initData.get(i.id),a=this.segments.get(i.id);if(t.assertNonNullable(s,'No init buffer for starting representation'),t.assertNonNullable(a,'No segments for starting representation'),!(s instanceof ArrayBuffer))return;let r=0;for(const t of a)t.time.from-r>=300&&this.gaps.push({representation:i.id,from:r,to:t.time.from}),r=t.time.to;t.isNonNullable(i.duration)&&i.duration-r>=300&&this.gaps.push({representation:i.id,from:r,to:i.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const i=this.representations.get(e);t.assertNonNullable(i,`No such representation ${e}`);let s=this.initData.get(e);if(t.isNullable(s)?yield this.loadInit(i,'high',!1):s instanceof Promise&&(yield s),s=this.initData.get(e),!(s&&s instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();t.isNonNullable(a)&&this.maintain(a)}.bind(this)),this.fetcher=r,this.tuning=o,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.container=s,s){case Bn.MP4:this.containerParser=Jn;break;case Bn.WEBM:this.containerParser=ol;break;default:t.assertNever(s)}this.initData=new Map(a.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(a.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Po,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer))return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(t.assertNonNullable(i,`No such representation ${this.downloadingRepresentationId}`),!s)return;const a=s.find((t=>e>=t.time.from&&e<t.time.to));let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=100,i=$n(this.sourceBuffer.buffered,e),s=a?a.time.to+t:-1/0;a&&i>=a.time.to-e+t&&(r=s)}if(isFinite(this.bufferLimit)&&Gn(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),a&&a.status!==On.NONE))return;let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,i.segmentReference.type,r),o.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))t='high';else{const e=Jo(o,0);e&&e.time.from-a.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(o,i,t)}!this.allInitsLoaded&&a&&a.status===On.FED&&!o.length&&$n(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const n=Jo(s,-1);n&&n.status===On.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===n))}findSegmentStartTime(t){var e,i,s;const a=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!a)return;const r=this.segments.get(a);if(!r)return;const o=r.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==o?void 0:o.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===On.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==Ln.BYTE_RANGE)return t.slice(s,s+1);const a=t;let r=0;const o=[];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!==On.NONE&&e.status!==On.PARTIALLY_EJECTED)break;o.push(e)}return o}async loadSegments(e,i,s='auto'){if(!e.length)return;let a,r,o=e;const{type:n}=i.segmentReference;switch(n){case Ln.BYTE_RANGE:a=i.segmentReference.url,r={from:Jo(e,0).byte.from,to:Jo(e,-1).byte.to};break;case Ln.TEMPLATE:{const t=Jo(e,0);a=new URL(t.url,i.segmentReference.baseUrl).toString(),o=[t];break}default:t.assertNever(n)}for(const t of o)t.status=On.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:i.id});const{signal:l}=this.downloadAbortController;if(this.failedDownloads&&(await t.abortable(l,async function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((t=>setTimeout(t,e)))}.bind(this))(),l.aborted))for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.fetcher.fetch(a,{rangeMethod:Hn.PARAM,range:r,onProgress:(e,s)=>{if(!l.aborted)try{this.onSomeDataLoaded(e,i.id,r?r.from:0,s,l)}catch(e){this.error$.next({id:'SegmentFeeding',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Error when feeding segments',thrown:e})}},signal:l,priority:s}).then((()=>this.failedDownloads=0),(t=>{for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.onSegmentDownloadError(t)}))}onSegmentDownloadError(e){var i;let s=!1;const a=this.getCurrentPosition();if(this.sourceBuffer&&t.isNonNullable(a)){s=$n(null===(i=this.sourceBuffer)||void 0===i?void 0:i.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,s||this.error$.next({id:'SegmentDownload',category:t.ErrorCategory.NETWORK,message:'Error when fetching segments',thrown:e})}onSomeDataLoaded(t,e,i,s,a){if(!this.activeSegments.size)return;const r=t=>{this.abortSegment(t.segment)},o=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=On.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===On.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=On.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},n=this.representations.get(e);if(!n)return;const l=n.segmentReference.type,u=t.byteLength;for(const n of this.activeSegments){const{segment:d}=n,h=l===Ln.BYTE_RANGE,c=h?d.byte.to-d.byte.from+1:u;if(n.representationId!==e)continue;if(!(!h||d.byte.from>=i&&d.byte.to<i+t.byteLength))continue;if(a.aborted){r(n);continue}const p=h?d.byte.from-i:0,m=p<s,f=(h?d.byte.to-i:t.byteLength)<=s;if(d.status===On.DOWNLOADING&&m&&f){d.status=On.DOWNLOADED,this.activeSegments.delete(n);const e=new DataView(t.buffer,t.byteOffset+p,c);this.sourceBufferTaskQueue.append(e,a).then((t=>t&&!a.aborted?o(n):r(n)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(n.loadedBytes=Math.min(c,s-p),n.loadedBytes>n.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+n.feedingBytes,n.loadedBytes-n.feedingBytes),i=n.loadedBytes===c?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(d.status=On.PARTIALLY_FED,n.feedingBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,a).then((t=>{if(a.aborted)r(n);else if(t)n.fedBytes+=i.byteLength,n.fedBytes===c&&o(n);else{if(n.feedingBytes<c)return;r(n)}})))}}}abortSegment(t){t.status===On.PARTIALLY_FED||t.status===On.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=On.NONE)),t.status=On.PARTIALLY_EJECTED):t.status=On.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||(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=Vn((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(e,i='auto',s=!1){const a=this.tuning.dash.useFetchPriorityHints?i:'auto',r=(!s&&this.failedDownloads>0?t.abortable(this.destroyAbortController.signal,async function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((t=>setTimeout(t,e)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a))).then((t=>{if(!t)return;const{dataView:i,segments:s}=t,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(e.id,a),this.segments.set(e.id,s)})).then((()=>this.failedDownloads=0),(i=>{this.initData.set(e.id,null),s&&this.error$.next({id:'LoadInits',category:t.ErrorCategory.WTF,message:'loadInit threw',thrown:i})}));return this.initData.set(e.id,r),r}async pruneBuffer(e){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let a=0,r=1/0,o=-1/0,n=!1;const l=t=>{var e;r=Math.min(r,t.time.from),o=Math.max(o,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;a+=i};for(const t of s){if(t.time.to>=i||a>=e)break;t.status===On.FED&&l(t)}if(n=isFinite(r)&&isFinite(o),!n){a=0,r=1/0,o=-1/0;for(const t of s){if(t.time.from<i+this.forwardBufferTarget||a>e)break;t.status===On.FED&&l(t)}}if(n=isFinite(r)&&isFinite(o),!n)for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),i=1e3*this.sourceBuffer.buffered.end(t);for(const t of s)if(t.status===On.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(i)){r=e,o=i;break}}return n=isFinite(r)&&isFinite(o),!!n&&this.sourceBufferTaskQueue.remove(r,o)}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(e,i){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Vn((()=>{try{this.detectGaps(e,i)}catch(e){this.error$.next({id:'GapDetection',category:t.ErrorCategory.WTF,message:'detectGaps threw',thrown:e})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=Math.round(1e3*this.sourceBuffer.buffered.start(t)),s=Math.round(1e3*this.sourceBuffer.buffered.end(t));e.push({from:i,to:s})}for(const t of this.segments.values())for(const i of t){const{status:t}=i;if(t!==On.FED&&t!==On.PARTIALLY_EJECTED)continue;const s=Math.round(i.time.from),a=Math.round(i.time.to),r=e.some((t=>t.from<=s&&t.to>=a)),o=e.some((t=>s>t.from&&s<t.to||a>t.from&&a<t.to));r||(i.status=o?On.PARTIALLY_EJECTED:On.NONE)}}}const ll=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},ul=(e,i)=>{let s=e;s=s.replaceAll('$$','$');const a={RepresentationID:i.representationId,Number:i.segmentNumber,Bandwidth:i.bandwidth,Time:i.segmentTime};for(const[e,i]of Object.entries(a)){const a=new RegExp(`\\$${e}(?:%0(\\d+)d)?\\$`,'g');s=s.replaceAll(a,((e,s)=>t.isNullable(i)?e:t.isNullable(s)?i:i.padStart(parseInt(s,10),'0')))}return s},dl=['timeupdate','progress','play','seeked','stalled'];var hl,cl;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(hl||(hl={}));class pl{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new fo(hl.NONE),this.currentVideoRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.forceEnded$=new t.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Po,this.initManifest=t.abortable(this.destroyController.signal,async function*(e,i){this.element=e,this.state$.startTransitionTo(hl.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(i).catch((e=>this.error$.next({id:'LoadManifest',category:t.ErrorCategory.NETWORK,message:'Failed to load manifest',thrown:e})));if(!s)return null;let a;try{a=((e,i)=>{var s,a,r,o,n,l,u,d,h,c,p,m,f,b,S,v,g,y,T,E,k,w,P,$,A,x,N,R,D,C,_,I,L,O,B;const M={video:[],audio:[],text:[]},V=(new DOMParser).parseFromString(e,'application/xml').children[0],F=V.getElementsByTagName('Period')[0],U=F.children;let q;const j=V.getAttribute('mediaPresentationDuration'),H=F.getAttribute('duration');if(j)q=ll(j);else if(H){const e=ll(H);t.isNonNullable(e)&&(q=e)}let G=0;const Y=null!==(a=null===(s=V.getAttribute('profiles'))||void 0===s?void 0:s.split(','))&&void 0!==a?a:[],Q=Y.includes(In.WEBM_AS_IN_FFMPEG)||Y.includes(In.WEBM_AS_IN_SPEC)?Bn.WEBM:Bn.MP4;for(const t of U){const e=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),a=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==e?void 0:e.split('/')[0],V=null!==(n=null===(o=t.getAttribute('profiles'))||void 0===o?void 0:o.split(','))&&void 0!==n?n:[],F=t.querySelectorAll('Representation');if('text'!==a)for(const r of F){const o=null!==(l=r.getAttribute('mimeType'))&&void 0!==l?l:e,n=null!==(d=null!==(u=r.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==d?d:'',F=null!==(c=null!==(h=r.getAttribute('contentType'))&&void 0!==h?h:null==o?void 0:o.split('/')[0])&&void 0!==c?c:a,U=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],j=parseInt(null!==(f=r.getAttribute('width'))&&void 0!==f?f:'',10),H=parseInt(null!==(b=r.getAttribute('height'))&&void 0!==b?b:'',10),Q=parseInt(null!==(S=r.getAttribute('bandwidth'))&&void 0!==S?S:'',10)/1e3,z=null!==(v=r.getAttribute('frameRate'))&&void 0!==v?v:'',W=null!==(g=r.getAttribute('quality'))&&void 0!==g?g:void 0,J=z?Yo(z):void 0,X=`${null!==(y=r.getAttribute('id'))&&void 0!==y?y:(G++).toString(10)}@${'video'===F?`${H}p`:'audio'===F?`${Q}Kbps`:n}`,K=null!==(k=null===(E=null===(T=r.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==k?k:'',Z=new URL(K,i).toString(),tt=[...Y,...V,...U];let et;const it=r.querySelector('SegmentBase'),st=r.querySelector('SegmentTemplate');if(it){const t=null!==(P=null===(w=r.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==P?P:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=null===($=r.querySelector('SegmentBase'))||void 0===$?void 0:$.getAttribute('indexRange'),[o,n]=a?a.split('-').map((t=>parseInt(t,10))):[],l=a?{from:o,to:n}:void 0;et={type:Ln.BYTE_RANGE,url:Z,initRange:s,indexRange:l}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(A=r.getAttribute('id'))&&void 0!==A?A:void 0,bandwidth:null!==(x=r.getAttribute('bandwidth'))&&void 0!==x?x:void 0},e=parseInt(null!==(N=st.getAttribute('timescale'))&&void 0!==N?N:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),a=null!==(C=parseInt(null!==(D=st.getAttribute('startNumber'))&&void 0!==D?D:'',10))&&void 0!==C?C:1,o=ul(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const n=null!==(_=st.querySelectorAll('SegmentTimeline S'))&&void 0!==_?_:[],l=[];let u=a,d=0;for(const i of n){const a=1e3*parseInt(null!==(I=i.getAttribute('d'))&&void 0!==I?I:'',10),r=parseInt(null!==(L=i.getAttribute('r'))&&void 0!==L?L:'',10)||0,o=null!==(B=parseInt(null!==(O=i.getAttribute('t'))&&void 0!==O?O:'',10))&&void 0!==B?B:void 0;for(let i=0;i<r+1;i++){const i=ul(s,{...t,segmentNumber:u.toString(10),segmentTime:o.toString(10)}),r=o?o/e:d;d+=a/e;const n=d;u++,l.push({time:{from:r,to:n},url:i})}}et={type:Ln.TEMPLATE,baseUrl:Z,initUrl:o,segments:l}}}if(!F||!o)continue;const at={video:_n.VIDEO,audio:_n.AUDIO,text:_n.TEXT}[F];at&&M[at].push({id:X,kind:at,segmentReference:et,profiles:tt,duration:q,bitrate:Q,mime:o,codecs:n,width:j,height:H,fps:J,quality:W})}}return{duration:q,container:Q,representations:M}})(null!=s?s:'',i)}catch(e){this.error$.next({id:'ManifestParsing',category:t.ErrorCategory.PARSER,message:'Failed to parse MPD manifest',thrown:e})}if(!a)return null;const r=({mime:t,codecs:i})=>{var s,a,r;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(r=null===(a=window.MediaSource)||void 0===a?void 0:a.isTypeSupported)||void 0===r?void 0:r.call(a,`${t}; codecs="${i}"`)))};return this.manifest={...a,representations:ao(Object.entries(a.representations).map((([t,e])=>[t,e.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(hl.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',category:t.ErrorCategory.PARSER,message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,async function*(e,i){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(hl.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new nl(_n.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],t.isNonNullable(i)&&(this.audioBufferManager=new nl(_n.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=t.merge(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(t.map((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),r=t.merge(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(t.map((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(t.merge(this.forceEnded$,t.combine({allBuffersFull:a,someBufferEnded:r}).pipe(t.filter((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var e;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(e=this.source)||void 0===e||e.endOfStream()}catch(e){this.error$.next({id:'EndOfStream',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Failed to end MediaSource stream',thrown:e})}}))),this.subscription.add(t.merge(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)}))),t.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&t.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(e),this.state$.setState(hl.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...dl.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(e=>{this.error$.next({id:'DashVKPlayer',category:t.ErrorCategory.WTF,message:'Internal logic error',thrown:e})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&Mn(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this)),this.tick=()=>{var e,i;if(!this.element||!this.videoBufferManager)return;const s=1e3*this.element.currentTime;this.videoBufferManager.maintain(s),null===(e=this.audioBufferManager)||void 0===e||e.maintain(s),!this.videoBufferManager.gaps.length&&!(null===(i=this.audioBufferManager)||void 0===i?void 0:i.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(e=>{this.error$.next({id:'GapWatchdog',category:t.ErrorCategory.WTF,message:'Error handling gaps',thrown:e})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Yn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(t,e){const i={[_n.VIDEO]:this.videoBufferManager,[_n.AUDIO]:this.audioBufferManager,[_n.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}seek(e,i){var s,a,r,o,n;let l;t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),l=i||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(null!==(s=this.videoBufferManager.findSegmentStartTime(e))&&void 0!==s?s:e,null!==(r=null===(a=this.audioBufferManager)||void 0===a?void 0:a.findSegmentStartTime(e))&&void 0!==r?r:e),Mn(this.element.buffered,l)||(this.videoBufferManager.abort(),null===(o=this.audioBufferManager)||void 0===o||o.abort()),this.videoBufferManager.maintain(l),null===(n=this.audioBufferManager)||void 0===n||n.maintain(l),this.element.currentTime=l/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(hl.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of this.bufferManagers)for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(cl||(cl={}));const ml=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{var o;const n=null!==(o=r?cn(r):void 0)&&void 0!==o?o:po({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},fl=(t,e,i)=>{var s;const a=e.indexOf(i);return null!==(s=Jo(t,Math.round(t.length*a/e.length)))&&void 0!==s?s:Jo(t,-1)};class bl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(cl.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new Vo,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new an,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(a.state===u.Requested&&(null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&e!==cl.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),i!==exports.PlaybackState.STOPPED){if(e===cl.STOPPED)return this.videoState.startTransitionTo(cl.READY),void this.prepare();switch(e){case cl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(cl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(cl.PLAYING),this.playIfAllowed()));case cl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(cl.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case cl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(cl.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==cl.STOPPED&&(this.videoState.startTransitionTo(cl.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(cl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=Fo(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(on(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new pl({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=Go(this.video),a=i=>{e.error$.next({id:'DashVKProvider',category:t.ErrorCategory.WTF,message:'DashVKProvider internal logic error',thrown:i})},r=(t,e)=>this.subscription.add(t.subscribe(e,a));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once(),t.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Lo(this.video,i.isLooped,a)),this.subscription.add(Oo(this.video,i.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Bo(this.video,i.playbackRate,s.playbackRateState$,a)),r(nn(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(cl.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),a)).add(s.pause$.subscribe((()=>{this.videoState.setState(cl.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),a)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===cl.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===hl.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(cl.READY)})));const o=i=>e.error$.next({id:'RepresentationSwitch',category:t.ErrorCategory.WTF,message:'Switching representations threw',thrown:i});this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var s,a,r,n,l,u,d,h;const c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c===hl.NONE||!this.videoTracks.length)return;const m=c===hl.MANIFEST_LOADED&&!p,f=c===hl.REPRESENTATION_SELECTED&&!p,b=i.autoVideoTrackSwitching.getState(),S=i.videoTrack.getState(),v=null===(s=this.videoTracks.find((({track:{id:t}})=>t===S)))||void 0===s?void 0:s.track,g=e.currentVideoTrack$.getValue(),y=$n(this.video.buffered,1e3*this.video.currentTime),T=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),k=Math.max(v&&!b&&null!==(r=null===(a=this.audioRepresentations.get(v.id))||void 0===a?void 0:a.bitrate)&&void 0!==r?r:0,g&&null!==(l=null===(n=this.audioRepresentations.get(g.id))||void 0===n?void 0:n.bitrate)&&void 0!==l?l:0),w=rn(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),reserve:k,forwardBufferHealth:E,current:g,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),P=b?null!=w?w:v:null!=v?v:w;if(i.autoVideoTrackSwitching.getTransition()&&(i.autoVideoTrackSwitching.setState(b),this.player.setBufferTarget(T)),m){const e=P&&(null===(u=this.videoTracks.find((({track:t})=>t===P)))||void 0===u?void 0:u.representation);t.assertNonNullable(e),this.player.initRepresentations(e.id,null===(d=this.audioRepresentations.get(e.id))||void 0===d?void 0:d.id)}else if(f){const t=P&&(null===(h=this.videoTracks.find((({track:t})=>t===P)))||void 0===h?void 0:h.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(_n.VIDEO,t.id).catch(o),e&&this.player.switchRepresentation(_n.AUDIO,e.id).catch(o)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.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=ml(t);if(s){this.videoTracks.push({track:s,representation:t});const a=fl(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)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(cl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const Sl={};var vl;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(vl||(vl={}));const gl=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class yl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(vl.INITIALIZING),this.textTracksManager=new Vo,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!==vl.INITIALIZING)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===u.Requested&&this.seek(a.position),i){case exports.PlaybackState.STOPPED:switch(e){case vl.STOPPED:break;case vl.READY:case vl.PLAYING:case vl.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case vl.PLAYING:break;case vl.STOPPED:this.prepare();break;case vl.READY:case vl.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case vl.PAUSED:break;case vl.STOPPED:this.prepare();break;case vl.READY:this.videoState.setState(vl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case vl.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Fo(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(on(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const s=i=>{e||this.params.output.error$.next({id:'timeout'===i?'HlsJsTimeout':'HlsJsLoadError',category:t.ErrorCategory.NETWORK,message:'Failed to load Hls.js',thrown:i}),e=!0},a=window.setTimeout((()=>s('timeout')),5e3);Promise.resolve().then((function(){return i(require('hls.js'))})).then((t=>{e||(Sl.Hls=t.default,Sl.Events=t.default.Events,this.init())}),s).finally((()=>{window.clearTimeout(a),e=!0}))}init(){t.assertNonNullable(Sl.Hls,'hls.js not loaded'),this.hls=new Sl.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(vl.STOPPED)}subscribe(){t.assertNonNullable(Sl.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=e=>{i.error$.next({id:'HlsJsProvider',category:t.ErrorCategory.WTF,message:'HlsJsProvider internal logic error',thrown:e})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,i.position$),r(a.durationChange$,i.duration$),r(a.ended$,i.endedEvent$),r(a.looped$,i.loopedEvent$),r(a.error$,i.error$),r(a.isBuffering$,i.isBuffering$),r(a.currentBuffer$,i.currentBuffer$),r(a.loadStart$,i.firstBytesEvent$),r(a.playing$,i.firstFrameEvent$),r(a.canplay$,i.canplay$),r(a.seeked$,i.seekedEvent$),this.subscription.add(Lo(this.video,e.isLooped,s)),this.subscription.add(Oo(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Bo(this.video,e.playbackRate,a.playbackRateState$,s)),this.subscription.add(gl(this.hls,Sl.Events.ERROR).subscribe((e=>{var s;e.fatal&&i.error$.next({id:['HlsJsFatal',e.type,e.details].join('_'),category:t.ErrorCategory.WTF,message:`HlsJs fatal ${e.type} ${e.details}, ${null===(s=e.err)||void 0===s?void 0:s.message} ${e.reason}`,thrown:e.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(vl.PLAYING),no(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(vl.PAUSED),no(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===vl.READY&&this.videoState.setState(vl.READY),this.videoState.getState()===vl.PLAYING&&this.playIfAllowed()}),s)),r(gl(this.hls,Sl.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const a=e.name||e.height.toString(10),{width:r,height:o}=e,n=null!==(s=cn(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:po({width:r,height:o});if(!n)return t;const l=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:a.toString(),quality:n,bitrate:e.bitrate/1e3,size:{width:r,height:o},fps:l};return this.trackLevels.set(a,{track:u,level:e}),t.push(u),t}),[])))),i.availableVideoTracks$),r(gl(this.hls,Sl.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>on(t)))),i.hostname$),this.subscription.add(Io(e.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const o=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},n=gl(this.hls,Sl.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>o(this.hls.levels[t]))));n.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(Io(e.videoTrack,(()=>{var t;return null===(t=o(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const a=this.hls.levels.indexOf(s),r=this.hls.currentLevel,o=this.hls.levels[r];!o||s.bitrate>o.bitrate?this.hls.nextLevel=a:(this.hls.loadLevel=a,this.hls.loadLevel=a)}),{changed$:n.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const l=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(vl.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(vl.PLAYING);await pn(this.video)||(this.videoState.setState(vl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(vl.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(vl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}var Tl=async t=>{const e=await wo(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0};const El=t=>{let e=null;if(t.QUALITY&&(e=cn(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=po({width:i,height:s})}return null!=e?e:null},kl=async(t,e=t)=>{var i;const s=await wo(t),a=(await s.text()).split('\n'),r=[];for(let t=0;t<a.length;t++){const s=a[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const o=ao(s[1].split(',').map((t=>t.split('=')))),n=null!==(i=o.QUALITY)&&void 0!==i?i:`stream-${o.BANDWIDTH}`,l=El(o);let u;o.BANDWIDTH&&(u=parseInt(o.BANDWIDTH,10)/1e3||void 0),!u&&o['AVERAGE-BANDWIDTH']&&(u=parseInt(o['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const d=o['FRAME-RATE']?parseFloat(o['FRAME-RATE']):void 0;let h;if(o.RESOLUTION){const[t,e]=o.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(h={width:t,height:e})}const c=new URL(a[++t],e).toString();l&&r.push({id:n,quality:l,url:c,bandwidth:u,size:h,fps:d})}return r};var wl,Pl,$l;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(wl||(wl={}));class Al{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new fo(wl.STOPPED),this.textTracksManager=new Vo,this.manifests$=new t.ValueSubject([]),this.liveOffset=new Uo,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==wl.STOPPED&&(this.videoState.startTransitionTo(wl.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(wl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===wl.STOPPED)return this.videoState.startTransitionTo(wl.READY),void this.prepare();if(a||r){const t=this.videoState.getState();return this.videoState.setState(wl.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(o.state===u.None&&this.params.desiredState.seekState.setState({state:u.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&o.state===u.Requested)return this.videoState.startTransitionTo(wl.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(e){case wl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(wl.PAUSED),this.liveOffset.pause(),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(wl.PLAYING),this.playIfAllowed()));case wl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(wl.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case wl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(wl.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case wl.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Fo(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),kl(oo(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',category:t.ErrorCategory.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:e}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(on(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),o=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const l=a?'master':o;return a&&!r&&s.startTransitionTo('master'),n.find((t=>t.id===l))}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'HlsLiveProvider',category:t.ErrorCategory.WTF,message:'HlsLiveProvider internal logic error',thrown:i})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.ended$,e.endedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(Oo(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Bo(this.video,i.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(wl.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(wl.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===wl.READY&&this.videoState.setState(wl.READY),this.videoState.getState()===wl.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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(on(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===wl.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&e.state===u.Requested&&this.seek(e.position)}),s)),this.subscription.add(a.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=oo(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',i),this.video.load(),Tl(i).then((e=>{var s;if(t.isNullable(e)){const e=null!==(s=this.params.source.maxSeekBackTime)&&void 0!==s?s:this.maxSeekBackTime$.getValue();if(t.isNullable(e)||!isFinite(e))try{wo(i).then((t=>t.text())).then((e=>{var s;const a=null===(s=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(e))||void 0===s?void 0:s[1];if(a){const e=new URL(a,i).toString();Tl(e).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(e)}))}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(wl.PAUSED),this.liveOffset.pause(),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Pl||(Pl={}));class xl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo(Pl.STOPPED),this.textTracksManager=new Vo,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Pl.STOPPED&&(this.videoState.startTransitionTo(Pl.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(Pl.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===Pl.STOPPED)return this.videoState.startTransitionTo(Pl.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(Pl.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(o.state===u.None&&this.params.desiredState.seekState.setState({state:u.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&o.state===u.Requested&&this.seek(o.position),e){case Pl.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Pl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Pl.PLAYING),this.playIfAllowed()));case Pl.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Pl.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Pl.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Pl.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Pl.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Fo(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(on(this.params.source.url)),kl(this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',category:t.ErrorCategory.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:e}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),o=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const l=a?'master':o;return a&&!r&&s.startTransitionTo('master'),n.find((t=>t.id===l))}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'HlsProvider',category:t.ErrorCategory.WTF,message:'HlsProvider internal logic error',thrown:i})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),r(a.seeked$,e.seekedEvent$),this.subscription.add(Lo(this.video,i.isLooped,s)),this.subscription.add(Oo(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Bo(this.video,i.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Pl.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Pl.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Pl.READY&&this.videoState.setState(Pl.READY),this.videoState.getState()===Pl.PLAYING&&this.playIfAllowed()}),s).add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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(on(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===Pl.CHANGING_MANIFEST&&this.videoState.setState(i.to),e.state===u.Requested&&this.seek(e.position)}),s))),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(Pl.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}($l||($l={}));class Nl{constructor(e){this.subscription=new t.Subscription,this.videoState=new fo($l.STOPPED),this.trackUrls={},this.textTracksManager=new Vo,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==$l.STOPPED&&(this.videoState.startTransitionTo($l.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($l.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(e===$l.STOPPED)return this.videoState.startTransitionTo($l.READY),void this.prepare();if(a){const{currentTime:t}=this.video;return this.prepare(),void(r.state===u.None&&this.params.desiredState.seekState.setState({state:u.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===u.Requested&&this.seek(r.position),e){case $l.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState($l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($l.PLAYING),this.playIfAllowed()));case $l.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo($l.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case $l.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo($l.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=Fo(e.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:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'MpegProvider',category:t.ErrorCategory.WTF,message:'MpegProvider internal logic error',thrown:i})},a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.loadedMetadata$,e.firstBytesEvent$),r(a.playing$,e.firstFrameEvent$),r(a.canplay$,e.canplay$),r(a.seeked$,e.seekedEvent$),this.subscription.add(Lo(this.video,i.isLooped,s)),this.subscription.add(Oo(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Bo(this.video,i.playbackRate,a.playbackRateState$,s)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState($l.PLAYING),no(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState($l.PAUSED),no(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===$l.READY&&this.videoState.setState($l.READY);const i=this.params.desiredState.videoTrack.getTransition();i&&t.isNonNullable(i.to)&&(this.params.desiredState.videoTrack.setState(i.to),this.params.output.currentVideoTrack$.next(this.trackUrls[i.to].track)),this.videoState.getState()===$l.PLAYING&&this.playIfAllowed()}),s)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:a}=this.trackUrls[s];t.assertNonNullable(a,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(a=Co(a)),this.video.setAttribute('src',a),this.video.load(),this.params.output.hostname$.next(on(a))}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState($l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}const Rl=['stun:videostun.mycdn.me:80'],Dl=()=>null;class Cl{constructor(t,e){this.ws=null,this.peerConnection=null,this.serverUrl='',this.streamKey='',this.stream=null,this.signalingType='JOIN',this.retryCount=0,this.externalStartCallback=Dl,this.externalStopCallback=Dl,this.externalErrorCallback=Dl,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:Rl}]};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(e){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',category:t.ErrorCategory.WTF,message:e.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:Rl,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var _l,Il,Ll,Ol,Bl,Ml,Vl,Fl,Ul,ql,jl,Hl,Gl,Yl,Ql,zl,Wl,Jl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(_l||(_l={}));class Xl{constructor(e){this.videoState=new fo(_l.STOPPED),this.maxSeekBackTime$=new t.ValueSubject(0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==_l.STOPPED&&(this.videoState.startTransitionTo(_l.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(_l.STOPPED),no(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===_l.STOPPED)return this.videoState.startTransitionTo(_l.READY),void this.prepare();if(a)this.prepare();else switch(e){case _l.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(_l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(_l.PLAYING),this.playIfAllowed()));case _l.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(_l.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case _l.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(_l.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=Fo(e.container),this.liveStreamClient=new Cl(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'WebRTCLiveProvider',category:t.ErrorCategory.WTF,message:'WebRTCLiveProvider internal logic error',thrown:i})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})}));const a=Go(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.liveTime$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe((t=>{e.duration$.next(t===1/0?0:t)}))).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===_l.READY&&this.videoState.setState(_l.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(_l.PAUSED)}),s)).add(a.playing$.subscribe((()=>{this.videoState.setState(_l.PLAYING)}),s)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Oo(this.video,i.volume,a.volumeState$,s)).add(a.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe((s=>{switch(s.to){case _l.STOPPED:e.position$.next(0),e.duration$.next(0),i.playbackState.setState(exports.PlaybackState.STOPPED);break;case _l.READY:break;case _l.PAUSED:i.playbackState.setState(exports.PlaybackState.PAUSED);break;case _l.PLAYING:i.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(s.to)}}),s)).add(t.merge(i.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s))}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(on(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=t,no(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(_l.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',category:t.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pn(this.video).then((t=>{t||(this.videoState.setState(_l.PAUSED),no(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}}class Kl{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 Zl=qo(),tu=(null===(Il=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Il?void 0:Il.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),eu=document.createElement('video'),iu={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Ol=null===(Ll=window.SourceBuffer)||void 0===Ll?void 0:Ll.prototype)||void 0===Ol?void 0:Ol.appendBuffer)),hls:Boolean((null===(Bl=eu.canPlayType)||void 0===Bl?void 0:Bl.call(eu,'application/x-mpegurl'))||(null===(Ml=eu.canPlayType)||void 0===Ml?void 0:Ml.call(eu,'vnd.apple.mpegURL'))),webrtc:Boolean(window.RTCPeerConnection)},su={mp4:Boolean(null===(Vl=eu.canPlayType)||void 0===Vl?void 0:Vl.call(eu,'video/mp4')),webm:Boolean(null===(Fl=eu.canPlayType)||void 0===Fl?void 0:Fl.call(eu,'video/webm'))},au={h264:Boolean(null===(ql=null===(Ul=window.MediaSource)||void 0===Ul?void 0:Ul.isTypeSupported)||void 0===ql?void 0:ql.call(Ul,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Hl=null===(jl=window.MediaSource)||void 0===jl?void 0:jl.isTypeSupported)||void 0===Hl?void 0:Hl.call(jl,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(Yl=null===(Gl=window.MediaSource)||void 0===Gl?void 0:Gl.isTypeSupported)||void 0===Yl?void 0:Yl.call(Gl,'video/webm; codecs="vp9"')),aac:Boolean(null===(zl=null===(Ql=window.MediaSource)||void 0===Ql?void 0:Ql.isTypeSupported)||void 0===zl?void 0:zl.call(Ql,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Jl=null===(Wl=window.MediaSource)||void 0===Wl?void 0:Wl.isTypeSupported)||void 0===Jl?void 0:Jl.call(Wl,'audio/webm; codecs="opus"'))},ru=(au.h264||au.h265)&&au.aac,ou=!Zl,nu=iu.hls&&su.mp4&&(tu||Zl),lu=Boolean(window.WebSocket);const uu=2e4,du=3,hu={cacheDuration:12e4},cu={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},pu={maxPausedTime:3e4},mu={maxPausedTime:3e4};class fu{constructor(e){this.current$=new t.ValueSubject({type:void 0}),this.providerError$=new t.Subject,this.noAvailableProvidersError$=new t.Subject,this.providerOutput={position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),volume$:new t.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new t.ValueSubject(void 0),availableVideoTracks$:new t.ValueSubject([]),autoVideoTrackLimitingAvailable$:new t.ValueSubject(!1),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),error$:new t.Subject,willSeekEvent$:new t.Subject,seekedEvent$:new t.Subject,loopedEvent$:new t.Subject,endedEvent$:new t.Subject,firstBytesEvent$:new t.Subject,firstFrameEvent$:new t.Subject,canplay$:new t.Subject,isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),element$:new t.ValueSubject(void 0)},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:i}=this.params.tuning,s=i.length?[...e.screenFormatsPriority.filter((t=>!i.includes(t))),...e.screenFormatsPriority.filter((t=>i.includes(t)))]:e.screenFormatsPriority;this.screenFormatsIterator=new Kl(((e,i=!1)=>e.filter((e=>{switch(e){case exports.VideoFormat.DASH:return iu.mse&&su.mp4&&ru&&ou;case exports.VideoFormat.DASH_SEP:return iu.mse&&su.mp4&&ru;case exports.VideoFormat.DASH_WEBM:return iu.mse&&su.webm&&au.vp9&&au.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return iu.mse&&su.mp4&&ru;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return nu||i&&iu.mse&&su.mp4&&ru;case exports.VideoFormat.MPEG:return su.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return iu.webrtc&&lu&&au.h264&&(su.mp4||su.webm);default:return t.assertNever(e)}})))(s.filter((i=>t.isNonNullable(e.sources[i]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Kl(e.chromecastFormatsPriority.filter((i=>t.isNonNullable(e.sources[i]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),i=this.chooseFormat(e);if(t.isNullable(i))return void this.handleNoFormatsError(e);let s;try{s=this.createProvider(e,i)}catch(e){this.providerError$.next({id:'ProviderNotConstructed',category:t.ErrorCategory.WTF,message:'Failed to create provider',thrown:e})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;t.assertNonNullable(e,'No current provider'),this.skipFormat(e),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!==u.None;this.params.desiredState.seekState.setState({state:u.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case o.SCREEN:return this.createScreenProvider(i);case o.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:a}=this.params,r=this.providerOutput,o={container:s,source:null,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new Cn({...o,source:s,config:hu})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),this.params.tuning.useDashJs?new hn({...o,source:s,format:e,config:mu}):new bl({...o,source:s})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),nu||!this.params.tuning.useHlsJs?new xl({...o,source:s}):new yl({...o,source:s})}case exports.VideoFormat.HLS_LIVE:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new Al({...o,source:s,config:pu})}case exports.VideoFormat.MPEG:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new Nl({...o,source:s})}case exports.VideoFormat.DASH_LIVE:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new wn({...o,source:s,config:cu})}case exports.VideoFormat.WEB_RTC_LIVE:{const o=this.applyFailoverHost(i[e]);return t.assertNonNullable(o),new Xl({container:s,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:a,meta:r}=this.params,o=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(n),new So({connection:n,meta:r,container:s,source:i,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?o.CHROMECAST:o.SCREEN}chooseFormat(e){switch(e){case o.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case o.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case o.SCREEN:return this.screenFormatsIterator.next();case o.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case o.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case o.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}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 ao(Object.entries(t).map((([t,e])=>[t,i(e)])))}initProviderErrorHandling(){const e=new t.Subscription;let i=!1,s=0;var a;return e.add(t.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:uu,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(t.filter((({type:t})=>void 0!==t)))},new t.Observable((e=>{const i=new t.Subscription,s=a.desiredPlaybackState$.stateChangeStarted$.pipe(t.map((({from:t,to:e})=>`${t}-${e}`))),r=a.desiredPlaybackState$.stateChangeEnded$,o=a.providerChanged$,n=new t.Subject;let l=0,u='unknown';return i.add(s.subscribe((t=>{l&&window.clearTimeout(l),u=t,l=window.setTimeout((()=>n.next(t)),a.maxTransitionInterval)}))),i.add(r.subscribe((()=>{window.clearTimeout(l),u='provider change',l=0}))),i.add(o.subscribe((()=>{l&&(window.clearTimeout(l),l=window.setTimeout((()=>n.next(u)),a.maxTransitionInterval))}))),i.add(n.subscribe(e)),()=>{window.clearTimeout(l),i.unsubscribe()}}))).pipe(t.map((e=>({id:`ProviderHangup:${e}`,category:t.ErrorCategory.WTF,message:`A ${e} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),e.add(this.current$.subscribe((()=>{i=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>i=!0));e.add(s)}))),e.add(this.providerError$.subscribe((e=>{if(this.current$.getValue().destination===o.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>this.switchToNextProvider()),(()=>this.params.dependencies.chromecastInitializer.disconnect()));else{const a=e.category===t.ErrorCategory.NETWORK,r=this.params.failoverHosts.length>0&&(void 0===this.failoverIndex||this.failoverIndex<this.params.failoverHosts.length-1),o=s<du;r&&(a&&i||!o)?(this.failoverIndex=void 0===this.failoverIndex?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}}))),e}}const bu=(t,e,i)=>i*e+(1-i)*t;class Su{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new en(`raw_${s}`),this.smoothedSeries$=new en(`smoothed_${s}`),this.reportedSeries$=new en(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let i=0,s=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(i+=(this.pastMeasures[t]-this.smoothed)**2,s++);i/=s;const a=Math.sqrt(i),r=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=bu(this.slow,e,this.params.emaAlphaSlow),this.fast=bu(this.fast,e,this.params.emaAlphaFast);const n=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=n(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>r||this.smoothed<o||(t.isNullable(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 vu;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(vu||(vu={}));const gu=new Map;let yu=vu.RUNTIME;const Tu=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Tu,'test'),localStorage.removeItem(Tu),yu=vu.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Tu),yu=vu.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;yu=vu.RUNTIME}}})();const Eu=(e,i)=>{switch(yu){case vu.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case vu.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case vu.RUNTIME:return void gu.set(e,i);default:t.assertNever(yu)}},ku=window.navigator.connection,wu=()=>{const e=null==ku?void 0:ku.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},Pu=()=>{const e=null==ku?void 0:ku.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},$u=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Au{constructor(e){var i,s;this.subscription=new t.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Au.load('one_video_throughput')||(e.useBrowserEstimation?wu():void 0)||5e3,r=null!==(s=null!==(i=Au.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?Pu():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(a),this.rtt$=new t.ValueSubject(r),this.rttAdjustedThroughput$=new t.ValueSubject($u(a,r,e.rttPenaltyRequestSize)),this.throughput=new Su({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Su({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=wu();e&&this.throughput.next(e);const i=Pu();t.isNonNullable(i)&&this.rtt.next(i)};ku&&'onchange'in ku&&this.subscription.add(t.fromEvent(ku,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Eu('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Eu('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(t.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(t.map((({throughput:t,rtt:i})=>$u(t,i,e.rttPenaltyRequestSize))),t.filter((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(e){let i=0,s=t.now();const a=new t.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:a.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}a.add(t.fromEvent(e,'loadend').subscribe((r=>{if(200===e.status){const e=r.loaded,a=t.now(),o=e-i,n=a-s;this.addRawSpeed(o,n,1)}this.concurrentDownloads.delete(e),a.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const a=t.now();let r=0,o=t.now();const n=t=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},l=async({done:u,value:d})=>{u?(this.addRawSpeed(s,t.now()-a,1),this.concurrentDownloads.delete(e)):d&&(s+=d.byteLength,r+=d.byteLength,r>=this.tuningConfig.streamMinSampleSize&&t.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,t.now()-o,this.concurrentDownloads.size),r=0,o=t.now()),await(null==i?void 0:i.read().then(l,n)))};this.concurrentDownloads.add(e),null==i||i.read().then(l,n)}addRawSpeed(t,e,i=1){if(Au.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(e){var i;const s=(e=>{var i,s;switch(yu){case vu.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case vu.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case vu.RUNTIME:return gu.get(e);default:t.assertNever(yu)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const xu={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.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 Nu=({playbackState:e,seekState:i,playbackAbort$:s,looped$:a,position$:r})=>new t.Observable((o=>{let n;const l=e.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),d=e.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),h=i.stateChangeEnded$.pipe(t.filter((({to:t})=>{var i,s;return t.state===u.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===exports.PlaybackState.PLAYING}))),c=i.stateChangeEnded$.pipe(t.filter((({from:t,to:i})=>{var s,a;return t.state===u.Applying&&i.state===u.None&&(null!==(a=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==a?a:e.getState())===exports.PlaybackState.PLAYING}))),p=t.merge(l,c).pipe(t.map((()=>r.getValue())),t.filter(t.isNonNullable)),m=t.merge(t.merge(d,h,s),a).pipe(t.map((()=>r.getValue())),t.filter(t.isNonNullable));return(new t.Subscription).add(p.subscribe((t=>{n=t}))).add(m.subscribe((e=>{if(t.isNullable(n)||n===e)return;const i={from:n,to:e};n=void 0,o.next(i)})))})),Ru={[o.SCREEN]:{vod:[...nu?[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:[],exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,...nu?[]:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND],exports.VideoFormat.MPEG],live:nu?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return t.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return t.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return t.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return t.ValueSubject}}),exports.Player=class{constructor(e={}){if(this.subscription=new t.Subscription,this.logger=new t.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new fo(exports.PlaybackState.STOPPED),seekState:new fo({state:u.None}),volume:new fo({volume:1,muted:!1}),videoTrack:new fo(void 0),autoVideoTrackSwitching:new fo(!0),autoVideoTrackLimits:new fo({}),isLooped:new fo(!1),playbackRate:new fo(1),externalTextTracks:new fo([]),currentTextTrack:new fo(void 0),textTrackCuesSettings:new fo({})},this.info={playbackState$:new t.ValueSubject(exports.PlaybackState.STOPPED),position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),muted$:new t.ValueSubject(!1),volume$:new t.ValueSubject(1),availableQualities$:new t.ValueSubject([]),availableQualitiesFps$:new t.ValueSubject({}),currentQuality$:new t.ValueSubject(void 0),isAutoQualityEnabled$:new t.ValueSubject(!0),autoQualityLimitingAvailable$:new t.ValueSubject(!1),autoQualityLimits$:new t.ValueSubject({}),currentPlaybackRate$:new t.ValueSubject(1),currentBuffer$:new t.ValueSubject({start:0,end:0}),isBuffering$:new t.ValueSubject(!0),isStalled$:new t.ValueSubject(!1),isEnded$:new t.ValueSubject(!1),isLooped$:new t.ValueSubject(!1),isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),currentFormat$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),throughputEstimation$:new t.ValueSubject(void 0),rttEstimation$:new t.ValueSubject(void 0),videoBitrate$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),chromecastState$:new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new t.ValueSubject(void 0),intrinsicVideoSize$:new t.ValueSubject(void 0)},this.events={inited$:new t.Subject,started$:new t.Subject,willPause$:new t.Subject,willResume$:new t.Subject,willDestruct$:new t.Subject,watchCoverageRecord$:new t.Subject,watchCoverageLive$:new t.Subject,managedError$:new t.Subject,fatalError$:new t.Subject,ended$:new t.Subject,looped$:new t.Subject,seeked$:new t.Subject,willSeek$:new t.Subject,firstBytes$:new t.Subject,firstFrame$:new t.Subject,canplay$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:Zo},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(xu)){const s=xu[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:null!=a?a:s}return e})(e),this.chromecastInitializer=new d({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Au(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(e,i,s)=>{const a=Reflect.get(e,i,s);return'function'!=typeof a?a:(...s)=>{try{return a.apply(e,s)}catch(e){const a=s.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(i)}`,o=`Exception calling ${r} (${a.join(', ')})`;throw this.events.fatalError$.next({id:r,category:t.ErrorCategory.WTF,message:o,thrown:e}),e}}}})}initVideo(e){var i,s,a;return this.config=e,this.domContainer=(e=>{const i='string'==typeof e.container?document.getElementById(e.container):e.container;return t.assertNonNullable(i,`Wrong container or containerId {${e.container}}`),i})(e),this.chromecastInitializer.contentId=null===(i=e.meta)||void 0===i?void 0:i.videoId,this.providerContainer=new fu({screenFormatsPriority:[...Ru[o.SCREEN].live,...Ru[o.SCREEN].vod],chromecastFormatsPriority:[...Ru[o.CHROMECAST].live,...Ru[o.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},failoverHosts:null!==(a=e.failoverHosts)&&void 0!==a?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PAUSED&&t.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.STOPPED&&t.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:u.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()===exports.ChromecastState.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()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.availableVideoTracks$.getValue();i.length||(this.explicitInitialQuality=e);const s=i.find((t=>t.quality===e));return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setPlaybackRate(e){var i;t.assertNonNullable(this.providerContainer);const s=null===(i=this.providerContainer)||void 0===i?void 0:i.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){t.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(e))return this.info.position$.getValue();const i=this.desiredState.seekState.getState(),s=i.state===u.None?void 0:i.position;return t.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((()=>!this.isPlaybackStarted)),t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{this.isPlaybackStarted=!0,this.events.started$.next()}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=t.now(),this.events.inited$.next())}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekState.getState();e.state===u.Requested?this.desiredState.seekState.setState({...e,state:u.Applying}):this.events.managedError$.next({id:`WillSeekIn${e.state}`,category:t.ErrorCategory.WTF,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===u.Applying&&(this.desiredState.seekState.setState({state:u.None}),this.events.seeked$.next())}))).add(e.current$.pipe(t.map((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(t.map((t=>t.destination)),t.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(t.map((t=>t.map((({quality:t})=>t)).sort(((t,e)=>mo(t)?1:mo(e)?-1:uo(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(t.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(t.filterChanged()).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(t.map((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(t.map((t=>t.muted)),t.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.volume)),t.filterChanged()).subscribe(this.info.volume$)).add((({seekState:e,position$:i})=>t.merge(e.stateChangeEnded$.pipe(t.map((({to:t})=>{var e;return t.state===u.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>e.getState().state===u.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(t.merge(e.providerOutput.endedEvent$.pipe(t.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(t.mapTo(!1))).pipe(t.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(t.map((e=>({id:'NoProviders',category:t.ErrorCategory.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(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let a=0;const r=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),a=i.getValue()||s.getValue();return t&&!a})),t.filterChanged());this.subscription.add(r.subscribe((t=>{t?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const o=new t.Subscription;this.subscription.add(o);const n=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),o.unsubscribe(),e){case!0:{const e=new t.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),o.add(Nu({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:e}).pipe(t.map((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(Nu({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).pipe(t.map((({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(t.map((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const i=new t.Subscription;this.subscription.add(i),this.subscription.add(e.current$.pipe(t.filterChanged(((t,e)=>t.provider===e.provider))).subscribe((()=>{i.unsubscribe(),i.add(e.providerOutput.availableVideoTracks$.pipe(t.filter((t=>t.length>0)),t.once()).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=rn(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(t.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(t.map((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput;t.assertNonNullable(this.providerContainer),t.assertNonNullable(i),Ko={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Xo=t})),this.providerContainer.current$.subscribe((({type:t})=>tn('provider',t))),i.duration$.subscribe((t=>tn('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>tn('tracks',t))),this.events.fatalError$.subscribe(new en('fatalError')),this.events.managedError$.subscribe(new en('managedError')),i.position$.subscribe(new en('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new en('quality')),this.info.currentBuffer$.subscribe(new en('buffer')),i.isBuffering$.subscribe(new en('isBuffering'))].forEach((t=>this.subscription.add(t))),tn('codecs',Object.keys(au).filter((t=>au[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.76';
|