@vkontakte/videoplayer-core 2.0.49 → 2.0.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/package.json +1 -1
- package/providers/DashProvider/utils/DashLite.d.ts +0 -60
package/esnext.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/playersdk/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.50
|
|
3
|
+
* Mon, 27 Jun 2022 09:53:35 GMT
|
|
4
|
+
* https://st.mycdn.me/static/playersdk/2-0-50/doc/
|
|
5
5
|
*/
|
|
6
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var e=require('@vkontakte/videoplayer-shared/esnext.cjs.js');function t(e){return e&&'object'==typeof e&&'default'in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if('default'!==s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var i=t(require('lodash/debounce'));var a,r,o,n,d,u,h;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_VK',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM_VK',r.DASH_ONDEMAND='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_JS',r.HLS_LIVE='HLS_LIVE',function(e){e.SCREEN='SCREEN',e.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.StartStatus=void 0,(d=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',d.SuccessWithoutSound='success_without_sound',d.Failed='failed',exports.HttpConnectionType=void 0,(u=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',u.HTTP2='http2',u.QUIC='quic',function(e){e.None='none',e.Requested='requested',e.Applying='applying'}(h||(h={}));class c{connection$=new e.ValueSubject(void 0);castState$=new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new e.Subject;contentId;realCastState$=new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new e.Subscription;log;params;constructor(t){this.params=t,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}`}),t.isDisabled||!s)return;var i;e.isNonNullable(window.chrome?.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{e&&this.initializeCastApi()},(i='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((e,t)=>{const s=document.createElement('script');s.setAttribute('src',i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)}))}toggleConnection(){e.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const s=this.connection$.getValue();e.isNullable(s)||(s.remotePlayer.volumeLevel=t,s.remotePlayerController.setVolumeLevel())}setMuted(t){const s=this.connection$.getValue();e.isNullable(s)||t!==s.remotePlayer.isMuted&&s.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,s=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(e.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return e.assertNever(t.sessionState)}}))).add(e.merge(e.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(e.tap((e=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(e)}`})})),e.map((e=>e.castState))),e.observableFrom([i.getCastState()])).pipe(e.filterChanged(),e.map(l),e.tap((e=>{this.log({message:`realCastState$: ${e}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{const r=a===exports.ChromecastState.CONNECTED,o=e.isNonNullable(this.connection$.getValue());if(r&&!o){const a=i.getCurrentSession();e.assertNonNullable(a);const r=a.getCastDevice(),o=a.getMediaSession()?.media.contentId;(e.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:s,session:a,castDevice:r}))}else!r&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?e.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)})))}initializeCastApi(){let e,t,s;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(e){return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(e){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:e})}}}const l=t=>{switch(t){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 e.assertNever(t)}};var p;!function(e){e[e.OFFSET_P=0]='OFFSET_P',e[e.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(p||(p={}));var m,S=(t,s=0,i=p.OFFSET_P)=>{switch(i){case p.OFFSET_P:return t.replace('_offset_p',0===s?'':'_'+s.toFixed(0));case p.PLAYBACK_SHIFT:{if(0===s)return t;const e=new URL(t);return e.searchParams.append('playback_shift',s.toFixed(0)),e.toString()}default:e.assertNever(i)}return t},f=(e,t,s=!1)=>{const i=e.getTransition();!s&&i&&i.to!==t||e.setState(t)};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}},g=(e,t)=>b[e].height>b[t].height,v=(e,t)=>b[e].height<b[t].height,y=Object.keys(b).sort(((e,t)=>v(e,t)?-1:1)),T=({width:e,height:t})=>{const s=Math.min(e,t),i=Math.max(e,t);return y.find((e=>{const t=b[e];return t.width>=i&&t.height>=s}))},E=e=>e===exports.VideoQuality.INVARIANT;class k{state;transition;transitionStarted$=new e.Subject;transitionEnded$=new e.Subject;transitionUpdated$=new e.Subject;forceChanged$=new e.Subject;stateChangeStarted$=e.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=e.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(t){const s=this.transition,i=this.state;i===t||e.isNonNullable(s)&&s.to===t||(this.state=t,s?(this.transition={from:s.from,to:t,canceledTransition:s},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var $;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}($||($={}));class P{subscription=new e.Subscription;loadMediaTimeoutSubscription=new e.Subscription;videoState=new k($.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:return!0;default:return e.assertNever(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const s=this.params.connection.session.getMediaSession();s&&this.restoreSession(s),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new e.Subscription;this.subscription.add(t),this.subscription.add(e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>`stateChangeStarted$ ${JSON.stringify(e)}`))),this.videoState.stateChangeEnded$.pipe(e.map((e=>`stateChangeEnded$ ${JSON.stringify(e)}`)))).subscribe((e=>this.log({message:`[videoState] ${e}`}))));const s=(e,t)=>this.subscription.add(e.subscribe(t));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new e.Subject;t.add(s.pipe(e.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let i=NaN;t.add(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((e=>{this.logRemoteEvent(e);const t=e.value;this.params.output.position$.next(t);(this.params.desiredState.seekState.getState().state===h.Applying||Math.abs(t-i)>5)&&s.next(t),i=t}))),t.add(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((e=>{this.logRemoteEvent(e),this.params.output.duration$.next(e.value)})))}s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemotePause():this.handleRemotePlay()})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:s}=this.params.connection,i=t.value,a=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),f(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:e.assertNever(i)}})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({volume:e.value})})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({muted:e.value})}));s(e.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)),this.syncPlayback)}restoreSession(e){this.log({message:'restoreSession'});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState($.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState($.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const e=this.params.output.isLive$.getValue();this.params.output.duration$.next(e?0:t.duration),this.params.output.position$.next(e?0:t.currentTime),this.params.desiredState.seekState.setState({state:h.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==$.PAUSED&&e!==$.PLAYING||(this.videoState.setState($.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==$.PLAYING&&e!==$.PAUSED||(this.videoState.setState($.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===$.READY&&this.videoState.setState($.READY)}handleRemoteStop(){this.videoState.getState()!==$.STOPPED&&this.videoState.setState($.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),s={volume:e.volume??t.volume,muted:e.muted??t.muted};s.volume===t.volume&&s.muted==s.muted||this.params.output.volume$.next(s)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(t){const s=this.params.source;let i,a,r;switch(t){case exports.VideoFormat.MPEG:{const o=s[t];e.assertNonNullable(o);const n=Object.keys(o).sort(((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:v(e,t)?1:-1))[0];e.assertNonNullable(n);const d=o[n];e.assertNonNullable(d),i=d,a='video/mp4',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const o=s[t];e.assertNonNullable(o),i=S(o.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/dash+xml',r=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:{const e='Unsupported format for Chromecast',t=new Error(e);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:e,thrown:t}),t}default:return e.assertNever(t)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);o.contentUrl=i,o.streamType=r,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:n,subtitle:d}=this.params.meta;return e.isNonNullable(n)&&(o.metadata.title=n),e.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===h.Applying||s.state===h.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(t){const s=this.params.connection.session.loadMedia(t),i=new Promise(((t,s)=>{this.loadMediaTimeoutSubscription.add(e.timeout(7e3).subscribe((()=>s('timeout(7000)'))))}));Promise.race([s,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===h.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(e=>{const t=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:t}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:t,thrown:e})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i!==exports.PlaybackState.STOPPED){if(!s)if(a?.to===exports.PlaybackState.PAUSED||r.state!==h.Requested||t===$.STOPPED)switch(i){case exports.PlaybackState.PLAYING:switch(t){case $.PLAYING:break;case $.PAUSED:case $.READY:this.videoState.startTransitionTo($.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case $.STOPPED:this.videoState.startTransitionTo($.READY),this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case $.PLAYING:this.videoState.startTransitionTo($.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case $.PAUSED:break;case $.READY:this.videoState.startTransitionTo($.PAUSED),this.videoState.setState($.PAUSED);break;case $.STOPPED:this.videoState.startTransitionTo($.READY),this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(i)}else this.seek(r.position)}else t!==$.STOPPED&&(this.videoState.startTransitionTo($.STOPPED),this.stop())}}class w{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let e=0,i=s.length;e<i;e++)if(s[e].callback===t)return void s.splice(e,1)}dispatchEvent(e){if(!(e.type in this.listeners))return;const t=this.listeners[e.type].slice();for(let s=0,i=t.length;s<i;s++){const i=t[s];try{i.callback.call(this,e)}catch(e){Promise.resolve().then((()=>{throw e}))}i.options&&i.options.once&&this.removeEventListener(e.type,i.callback)}return!e.defaultPrevented}}class A extends w{constructor(){super(),this.listeners||w.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(e){'abort'===e.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class x{constructor(){Object.defineProperty(this,'signal',{value:new A,writable:!0,configurable:!0})}abort(){let e;try{e=new Event('abort')}catch(t){'undefined'!=typeof document?document.createEvent?(e=document.createEvent('Event'),e.initEvent('abort',!1,!1)):(e=document.createEventObject(),e.type='abort'):e={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(e)}toString(){return'[object AbortController]'}}function N(e){return e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof e.Request&&!e.Request.prototype.hasOwnProperty('signal')||!e.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(x.prototype[Symbol.toStringTag]='AbortController',A.prototype[Symbol.toStringTag]='AbortSignal');const _=N({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),D=_?function(e){'function'==typeof e&&(e={fetch:e});const{fetch:t,Request:s=t.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=e;if(!N({fetch:t,Request:s,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:t,Request:r};let r=s;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(e,t){let i;t&&t.signal&&(i=t.signal,delete t.signal);const a=new s(e,t);return i&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:i}),a},r.prototype=s.prototype);const o=t;return{fetch:(e,t)=>{const s=r&&r.prototype.isPrototypeOf(e)?e.signal:t?t.signal:void 0;if(s){let i;try{i=new DOMException('Aborted','AbortError')}catch(e){i=new Error('Aborted'),i.name='AbortError'}if(s.aborted)return Promise.reject(i);const a=new Promise(((e,t)=>{s.addEventListener('abort',(()=>t(i)),{once:!0})}));return t&&t.signal&&delete t.signal,Promise.race([a,o(e,t)])}return o(e,t)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,R=_?D.fetch:window.fetch;_?D.Request:window.Request;const I=_?x:window.AbortController,C=e=>e.range?e.range.split('-').map((e=>parseInt(e,10))):[NaN,NaN];class L{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[a,r]=C(i.request);if(a>=s.from&&r<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map((({request:e})=>e)));this.activeRequests.set(e,s)}}}abort(e){if(e){const{request:t}=e,s=(this.dashJsRequestQueue.get(t.url)??[]).includes(e),i=this.activeRequests.get(t.url);s&&i&&i.abortController.abort()}else for(const{abortController:e}of this.activeRequests.values())e.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(C),i=s[0][0];let a=s[0][1];for(let e=1;e<s.length&&a<this.params.minDataSize;e++){const t=s[e][1];t-i<=2*this.params.minDataSize&&(a=Math.max(a,t))}a=0===i?Math.max(a,i+this.params.minInitSize):Math.max(a,i+this.params.minDataSize);const r=new URL(e,location.href);r.searchParams.append('bytes',`${i}-${a}`);const o=r.toString(),n=new I,d=n.signal,u={url:e,from:i,to:a,loaded:0,data:null,abortController:n};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=e=>{throw this.params.onError?.({id:'BigRequestParsing',message:'Error parsing response data',thrown:e}),e};return R(o,{signal:d}).then((e=>{if(!e.ok||!e.body)return void this.onBigRequestError(u);const[t,s]=e.body.tee();this.params.onDownloadStream?.(s);const i=t.getReader(),a=parseInt(e.headers.get('Content-Length')??'',10);u.data=new ArrayBuffer(a);const r=new Uint8Array(u.data),o=async({done:e,value:t})=>{e?this.onBigRequestProgress(u):t&&(r.set(t,u.loaded),u.loaded+=t.byteLength,this.onBigRequestProgress(u),await(i?.read().then(o,L.suppressStreamErrors).catch(h)))};i?.read().then(o,L.suppressStreamErrors).catch(h)}),L.suppressAbort).catch((e=>this.onBigRequestError(u,e))),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a}){if(!this.activeRequests.has(e)||!a)return;const r=this.dashJsRequestQueue.get(e)??[];for(const o of r){const{request:r}=o,[n,d]=C(r),u=n>=t&&d<=t+i,h=t>=n&&t+i<d,c=a.slice(n-t,Math.min(d-t+1,i));(u||h)&&(r.requestStartDate=r.requestStartDate??new Date,r.firstByteDate=r.firstByteDate??new Date,r.bytesLoaded=c.byteLength,r.bytesTotal=s-t),u?(r.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter((e=>e!==o))),o.success?.(c,'',e),this.dashMetrics?.addHttpRequest(r,e,200,{},[])):h&&o.progress?.({loaded:i,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},i){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:i}),!this.activeRequests.has(e))return;const a=this.dashJsRequestQueue.get(e)??[];for(const e of a){const[a,r]=C(e.request);(a>=t&&a<s||r>t&&r<=s)&&e?.error?.(e.request,String(i))}if(this.activeRequests.delete(e),i)throw i}onBigRequestAbort({url:e,from:t,to:s}){if(!this.activeRequests.has(e))return;const i=this.dashJsRequestQueue.get(e)??[];for(const e of i){const[i,a]=C(e.request);(i>=t&&i<s||a>t&&a<=s)&&e?.abort?.(e.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e}static suppressStreamErrors(){}}class B{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return'download'!==e.action||'text'===e.mediaType||!e.range||'arraybuffer'!==e.responseType}load(e){const{request:t}=e;if(B.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:t}=e;B.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const O=(e,t)=>{const s=new L(t);return e.extend('SchemeLoaderFactory',(function(){const{parent:e}=this,t=e.getLoader;return{getLoader:e=>((e,t)=>s=>({create:i=>{const a=e(s).create(i);return new B(a,t,i)}}))(t(e),s)}}),!0),()=>s.destroy()};var V=e=>{let t,s=!1,i=!1;e.on('playbackTimeUpdated',(({timeToEnd:e})=>{i=e<=3,s&&i&&t?.()})),e.extend('MediaSourceController',(function(){const{parent:e}=this,a=e.signalEndOfStream;return{signalEndOfStream:e=>{s=!0,t=()=>a(e),s&&i&&t?.()}}}),!0)},M=t=>{const s=new e.ValueSubject(1/0),i=new e.Subject;let a=NaN,r=!1;return t.extend('XHRLoader',(function(){const{parent:t}=this,o=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const o=t.onload,n=t.progress;t.onload=function(...t){return(t=>{if(!t.getAllResponseHeaders().includes('x-playback-duration'))return;const i=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),a=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*i??NaN;e.isNonNullable(a)&&!isNaN(a)&&s.next(a)})(this),o(...t)},t.progress=function(...e){return this.readyState>=2&&!r&&(r=!0,i.next(Date.now()-a)),n(...e)},a=Date.now(),r=!1}return o(t)}}}),!0),{playbackDuration$:s,ping$:i}},F=e=>{const t=new URL(e);return t.searchParams.append('quic','1'),t.toString()},U=e=>{e.extend('HTTPLoader',(function(){const{parent:e}=this,t=e.load;return{load:e=>{if(e.request&&e.request.range){const[t,s]=e.request.range.split('-').map((e=>parseInt(e,10))),i=new URL(e.request.url,location.href);i.searchParams.append('bytes',`${t}-${s}`),e.request.url=i.toString(),e.request.range=void 0}t(e)}}}),!0)};const q=(t,s,i,{equal:a=((e,t)=>e===t),changed$:r,onError:o}={})=>{const n=t.getState(),d=s(),u=e.isNullable(r),h=new e.Subscription;return r&&h.add(r.subscribe((e=>{const s=t.getState();a(e,s)&&t.setState(e)}),o)),a(d,n)||(i(n),u&&t.setState(n)),h.add(t.stateChangeStarted$.subscribe((e=>{i(e.to),u&&t.setState(e.to)}),o)),h},H=(t,s,i)=>q(s,(()=>t.loop),(s=>{e.isNonNullable(s)&&(t.loop=s)}),{onError:i}),j=(t,s,i,a)=>q(s,(()=>({muted:t.muted,volume:t.volume})),(s=>{e.isNonNullable(s)&&(t.muted=s.muted,t.volume=s.volume)}),{equal:(e,t)=>e===t||e?.muted===t?.muted&&e?.volume===t?.volume,changed$:i,onError:a}),G=(e,t)=>{if(e.id===t)return!0;const[s,i,a]=t.split('|');return e.language===i&&e.label===a};class Y{available$=new e.Subject;current$=new e.ValueSubject(void 0);error$=new e.Subject;video;cueSettings;subscription=new e.Subscription;externalTracks=new Map;connect(t,s,i){this.video=t,this.cueSettings=s.textTrackCuesSettings,this.subscribe();const a=e=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:e})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(q(s.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{e.isNonNullable(t)&&this.setExternal(t)}),{equal:(t,s)=>e.isNonNullable(t)&&e.isNonNullable(s)&&t.length===s.length&&t.every((({id:e},t)=>e===s[t].id)),changed$:this.available$.pipe(e.map((e=>e.filter((({type:e})=>'external'===e))))),onError:a})),this.subscription.add(q(s.currentTextTrack,(()=>{if(this.video)return;const e=this.htmlTextTracksAsArray().find((({mode:e})=>'showing'===e));return e&&this.htmlTextTrackToITextTrack(e).id}),(e=>this.select(e)),{changed$:this.current$,onError:a})),this.subscription.add(q(s.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const e of this.htmlTextTracksAsArray())this.applyCueSettings(e.cues),this.applyCueSettings(e.activeCues)})))}subscribe(){e.assertNonNullable(this.video);const{textTracks:t}=this.video;this.subscription.add(e.fromEvent(t,'addtrack').subscribe((()=>{const e=this.current$.getValue();this.select(e)}))),this.subscription.add(e.merge(e.fromEvent(t,'addtrack'),e.fromEvent(t,'removetrack'),e.observableFrom(['init'])).pipe(e.map((()=>this.htmlTextTracksAsArray().map((e=>this.htmlTextTrackToITextTrack(e))))),e.filterChanged(((e,t)=>e.length===t.length&&e.every((({id:e},s)=>e===t[s].id))))).subscribe(this.available$)),this.subscription.add(e.merge(e.fromEvent(t,'change'),e.observableFrom(['init'])).pipe(e.map((()=>this.htmlTextTracksAsArray().find((({mode:e})=>'showing'===e)))),e.map((e=>e&&this.htmlTextTrackToITextTrack(e).id)),e.filterChanged()).subscribe(this.current$));const s=e=>this.applyCueSettings(e.target?.activeCues??null);this.subscription.add(e.fromEvent(t,'addtrack').subscribe((e=>{e.track?.addEventListener('cuechange',s);const t=e=>{const s=e.target?.cues??null;s&&s.length&&(this.applyCueSettings(e.target?.cues??null),e.target?.removeEventListener('cuechange',t))};e.track?.addEventListener('cuechange',t)}))),this.subscription.add(e.fromEvent(t,'removetrack').subscribe((e=>{e.track?.removeEventListener('cuechange',s)})))}applyCueSettings(t){if(!t||!t.length)return;const s=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;e.isNonNullable(s.align)&&(t.align=s.align),e.isNonNullable(s.position)&&(t.position=s.position),e.isNonNullable(s.size)&&(t.size=s.size),e.isNonNullable(s.line)&&(t.line=s.line)}}htmlTextTracksAsArray(t=!1){e.assertNonNullable(this.video);const s=[...this.video.textTracks];return t?s:s.filter(Y.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=''!==e.id?e.id:(e=>['__',e.language,e.label].join('|'))(e);return this.externalTracks.has(i)?{id:i,type:'external',language:t,label:s,url:this.externalTracks.get(i).url}:{id:i,type:'internal',language:t,label:s}}static isHealthyTrack(e){return'metadata'!==e.kind&&(''!==e.id||''!==e.label||''!==e.language)}setExternal(e){e.filter((({id:e})=>!this.externalTracks.has(e))).forEach((e=>this.attach(e))),Array.from(this.externalTracks.keys()).filter((t=>!e.find((e=>e.id===t)))).forEach((e=>this.detach(e)))}select(t){e.assertNonNullable(this.video);for(const s of this.htmlTextTracksAsArray(!0))e.isNonNullable(t)&&G(s,t)?s.mode='showing':s.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName('track'))){const t=e.getAttribute('id');t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(t){e.assertNonNullable(this.video);const s=document.createElement('track');s.setAttribute('src',t.url),s.setAttribute('id',t.id),t.label&&s.setAttribute('label',t.label),t.language&&s.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(s)}detach(t){e.assertNonNullable(this.video);const s=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));s&&this.video.removeChild(s),this.externalTracks.delete(t)}}var Q=e=>{const t=document.createElement('video');return t.setAttribute('crossorigin','anonymous'),t.setAttribute('playsinline','playsinline'),e.appendChild(t),t};class z{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var W=t=>new e.Observable((s=>{let i=0;return(new e.Subscription).add(e.fromEvent(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(e.fromEvent(t,'loadeddata').subscribe((()=>{s.next(Date.now()-i)})))})).pipe(e.once());class J{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let s=this._source.buffered.start(t);const i=this._source.buffered.end(t);s>e&&s-e<3&&(s=e),this._buffer.push({start:s,end:i,i:t})}return this._buffer.sort((function(e,t){return e.start-t.start})),this._buffer}getByTime(e){return this._buffer.find((t=>e>=t.start&&e<t.end))}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.start-e.end<(t||3))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach((({start:i,end:a})=>{const r=i>=e&&i<t,o=a>=e&&a<t;r&&o||(r?s(t,a):o?s(i,e):i<e&&a>t?(s(t,a),s(i,e)):s(i,a))}))}destroy(){this._buffer=[]}}var K=(e,t,s=3)=>{let i=0,a=0;for(let r=0;r<e.length;r++){const o=e.start(r),n=e.end(r);if(o<=t&&t<=n){if(i=o,a=n,!s)return{start:i,end:a};for(let t=r-1;t>=0;t--)e.end(t)+s>=i&&(i=e.start(t));for(let t=r+1;t<e.length;t++)e.start(t)-s<=a&&(a=e.end(t))}}return{start:i,end:a}},X=t=>new e.Observable((s=>{let i=0;return(new e.Subscription).add(e.fromEvent(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(e.fromEvent(t,'loadedmetadata').subscribe((()=>{s.next(Date.now()-i)})))})).pipe(e.once());const Z=t=>{const s=(s,i=(()=>{}))=>e.fromEvent(t,s).pipe(e.map(i)),i=e.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((s=>e.fromEvent(t,s)))).pipe(e.map((()=>t.readyState<3)),e.filterChanged()),a=e.merge(e.fromEvent(t,'progress'),e.fromEvent(t,'timeupdate')).pipe(e.map((()=>K(t.buffered,t.currentTime)))),r=e.fromEvent(t,'volumechange').pipe(e.debounce(0),e.map((()=>({muted:t.muted,volume:t.volume})))),o=e.fromEvent(t,'error').pipe(e.map((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),n=s('timeupdate',(()=>t.currentTime)),d=new e.Subject;let u;return n.subscribe((s=>{t.loop&&e.isNonNullable(u)&&e.isNonNullable(s)&&u>=t.duration-.3&&s<=.3&&d.next(u),u=s})),{playing$:s('playing'),pause$:s('pause'),canplay$:s('canplay'),ended$:s('ended'),looped$:d,error$:o,seeked$:s('seeked'),seeking$:s('seeking'),progress$:s('progress'),loadedMetadata$:s('loadedmetadata'),loadedData$:s('loadeddata'),timeUpdate$:n,durationChange$:s('durationchange',(()=>t.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:r,firstBytes$:X(t),firstFrame$:W(t)}},ee=e=>{if(e.includes('/')){const t=e.split('/');return parseInt(t[0])/parseInt(t[1])}return parseFloat(e)};let te=!1,se={};const ie=e=>{e(se)},ae=(e,t)=>{te&&(se.meta=se.meta??{},se.meta[e]=t)};class re{name;constructor(e){this.name=e}next(e){if(!te)return;se.series=se.series??{};const t=se.series[this.name]??[];t.push([Date.now(),e]),se.series[this.name]=t}}const oe=new re('best_bitrate'),ne=(t,{container:s,throughput:i,tuning:a,limits:r,forwardBufferHealth:o,currentRepresentation:n})=>{const d=a.usePixelRatio?window.devicePixelRatio??1:1,u=a.limitByContainer&&s&&s.width>0&&s.height>0&&{width:s.width*d*a.containerSizeFactor,height:s.height*d*a.containerSizeFactor},h=u&&T(u),c=t.filter((e=>!E(e.quality))).sort(((e,t)=>g(e.quality,t.quality)?-1:1)),l=c.at(-1)?.quality,p=c.at(0)?.quality,m=e.isNullable(r)||e.isNonNullable(r.min)&&e.isNonNullable(r.max)&&v(r.max,r.min)||e.isNonNullable(r.min)&&p&&g(r.min,p)||e.isNonNullable(r.max)&&l&&v(r.max,l),S=c.filter((t=>{const s=!h||v(t.quality,h),d=!(e.isNonNullable(i)&&isFinite(i)&&e.isNonNullable(t.bitrate))||i>=t.bitrate*(u=o??.5,c=a.bitrateFactorAtEmptyBuffer,l=a.bitrateFactorAtFullBuffer,(c-l)*Math.pow(2,-10*u)+l);var u,c,l;const p=!a.lazyQualitySwitch||!n||(o??.5)>=.5||(t.size?.height||0)<=(n?.height||0),S=m||(e.isNullable(r.max)||(f=t.quality,g=r.max,b[f].height<=b[g].height))&&(e.isNullable(r.min)||((e,t)=>b[e].height>=b[t].height)(t.quality,r.min));var f,g;return s&&d&&p&&S}))[0];return S&&S.bitrate&&oe.next(S.bitrate),S??c[Math.ceil((c.length-1)/2)]??t[0]};var de=e=>new URL(e).hostname;const ue=(t,s=300)=>new e.Observable((a=>{const{width:r,height:o}=t.getBoundingClientRect();if(a.next({width:r,height:o}),!window.ResizeObserver)return;const n=new ResizeObserver(i.default((t=>{const s=t[0];if(!s)return;let i,r;s.contentBoxSize&&s.contentBoxSize[0]?(r=s.contentBoxSize[0].blockSize,i=s.contentBoxSize[0].inlineSize):s.contentRect&&(i=s.contentRect.width,r=s.contentRect.height),e.isNonNullable(i)&&e.isNonNullable(r)&&a.next({width:i,height:r})}),s));return n.observe(t),()=>n.disconnect()})),he={};var ce;!function(e){e.DOWNLOADING_LIB='downloading_lib',e.STOPPED='stopped',e.STREAM_INITIALIZED='stream_initialized',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ce||(ce={}));const le=(t,s)=>new e.Observable((e=>{const i=t=>e.next(t);return t.on(s,i),()=>t.off(s,i)}));class pe{subscription=new e.Subscription;videoState=new k(ce.DOWNLOADING_LIB);video;player;params;textTracksManager=new Y;videoTracks=[];frameRatesByFrameHeight={};isLive$=new e.ValueSubject(void 0);maxSeekBackTime$=new e.ValueSubject(1/0);availableFrom$=new e.ValueSubject(void 0);elementSize$=new e.ValueSubject(void 0);liveOffset=new z;destroyBigRequest;constructor(e){this.video=Q(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=t=>{e||this.params.output.error$.next({id:'timeout'===t?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${t?.toString?.()}`,thrown:t}),e=!0},i=window.setTimeout((()=>t('timeout')),5e3);Promise.resolve().then((function(){return s(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((t=>{e||(he.MediaPlayer=t.MediaPlayer,he.Debug=t.Debug,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(he.MediaPlayer,'dashjs not loaded'),e.assertNonNullable(he.Debug,'dashjs not loaded'),this.player=he.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((e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?ee(e.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=O(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:e=>this.params.output.error$.next(e),onDownloadStream:e=>this.params.dependencies.throughputEstimator.trackStream(e)}):this.params.tuning.stripRangeHeader&&U(this.player),V(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:F})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(ce.STOPPED)}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(e,t)=>this.subscription.add(e.subscribe(t,i));a(ue(this.video),this.elementSize$),a(le(this.player,'error').pipe(e.map((e=>({id:`DashJS#${'object'==typeof e.error?e.error.code:e.error}`,message:'object'==typeof e.error?e.error.message:void 0})))),t.error$),a(le(this.player,'playbackError').pipe(e.map((e=>({id:'DashJSPlayback',message:e.error})))),t.error$);const r=le(this.player,'qualityChangeRendered').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({newQuality:e})=>this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===e))?.track)));r.pipe(e.filter(e.isNonNullable)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(e.filter((({to:e})=>e===ce.STREAM_INITIALIZED)),e.once()).subscribe((()=>{this.subscription.add(q(s.videoTrack,(()=>{const e=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===e))?.track?.id}),(t=>{if(e.isNullable(t))return;const s=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(e.map((e=>e?.id))),onError:i}))}),i)),this.subscription.add(q(s.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(e=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:e}}}})),{onError:i})),a(le(this.player,'bufferStateChanged').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({state:e})=>'bufferStalled'===e))),t.isBuffering$),a(le(this.player,'fragmentLoadingStarted').pipe(e.map((e=>de(e.request.url)))),t.hostname$),a(le(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:s,availableFrom:i}}})=>{this.isLive$.next(s),this.availableFrom$.next(i.getTime()),s||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const e of this.player.getBitrateInfoListFor('video')){const t=e.qualityIndex.toString(10),s=T(e),i=e.bitrate/1e3,o={width:e.width,height:e.height},n=this.frameRatesByFrameHeight[e.height];if(s){const d={id:t,quality:s,bitrate:i,size:o,fps:n};this.videoTracks.push({track:d,bitrateInfo:e}),e.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:e})=>e))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(ce.STREAM_INITIALIZED),this.videoState.startTransitionTo(ce.READY)})),a(le(this.player,'fragmentLoadingCompleted'),(({request:e})=>{if(!e.requestEndDate||!e.firstByteDate||!e.bytesLoaded)return;const t=e.requestEndDate.getTime()-e.firstByteDate.getTime(),s=e.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(s,t)})),a(e.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,s.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const e=this.params.dependencies.throughputEstimator.throughput$.getValue(),t=ne(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:e,tuning:this.params.tuning.autoTrackSelection,limits:s.autoVideoTrackLimits.getState()}),i=this.videoTracks.find((({track:e})=>e===t));i?.bitrateInfo&&this.player.setQualityFor('video',i?.bitrateInfo.qualityIndex,!1)})),a(e.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(e.filter(e.isNonNullable))}).pipe(e.filter((({isLive:e})=>e)),e.map((({maxSeekBackTime:e})=>-e/1e3))),this.params.output.duration$);const o=le(this.player,'playbackTimeUpdated').pipe(e.map((({time:e})=>e??0)));a(e.combine({availableFrom:this.availableFrom$.pipe(e.filter(e.isNonNullable)),currentTime:o}),(({availableFrom:e,currentTime:t})=>this.params.output.liveTime$.next(e+1e3*t))),a(o.pipe(e.filter((()=>!1===this.isLive$.getValue()))),t.position$),a(le(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(le(this.player,'playbackEnded'),t.endedEvent$),a(le(this.player,'playbackProgress').pipe(e.map((()=>K(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(le(this.player,'playbackPlaying'),(()=>{this.videoState.setState(ce.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)})),a(le(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(ce.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(le(this.player,'playbackPaused'),(()=>{this.videoState.setState(ce.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)})),a(le(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY)})),a(this.isLive$,t.isLive$),a(ue(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)),this.syncPlayback);const{playbackDuration$:n,ping$:d}=M(this.player);a(n,this.maxSeekBackTime$),a(d.pipe(e.once()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&a(e.combine({isLive:this.isLive$,isShort:t.duration$.pipe(e.map((e=>e<60)))}),(({isLive:e,isShort:t})=>{const s=!e&&t;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:s}}})})),a(o.pipe(e.filter((e=>e>this.params.tuning.insufficientBufferRuleMargin)),e.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,s,t),this.subscription.add(le(this.player,'manifestLoaded').pipe(e.once()).subscribe((()=>{const s=Date.now();this.subscription.add(le(this.player,'playbackPlaying').pipe(e.once()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-s)),i))}),i)),this.subscription.add(H(this.video,s.isLooped,i));const{volumeState$:u,looped$:h}=Z(this.video);this.subscription.add(j(this.video,s.volume,u,i)),this.subscription.add(u.subscribe(t.volume$,i)),this.subscription.add(h.subscribe(t.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(ce.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(ce.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const i=S(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,p.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(ce.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==ce.DOWNLOADING_LIB&&t!==ce.STREAM_INITIALIZED)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===h.Requested&&t!==ce.STOPPED&&s!==exports.PlaybackState.STOPPED&&(r?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case exports.PlaybackState.STOPPED:switch(t){case ce.STOPPED:break;case ce.PLAYING:case ce.PAUSED:case ce.READY:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case ce.PLAYING:break;case ce.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 ce.READY:this.play();break;case ce.STOPPED:this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case ce.PLAYING:this.pause(),this.liveOffset.pause();break;case ce.PAUSED:break;case ce.READY:this.videoState.setState(ce.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case ce.STOPPED:this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(e){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var me=e=>{switch(e){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}},Se=async e=>{const t=e.muted;try{await e.play()}catch(s){if(s instanceof DOMException&&(20===s.code||'AbortError'===s.name))return!1;if(t)return console.warn(s),!1;e.muted=!0;try{await e.play()}catch(t){return e.muted=!1,console.warn(t),!1}}return!0};function fe(){return e.now()}function be(e){return fe()-e}function ge(e){const t=e.split('/'),s=t.slice(0,t.length-1).join('/'),i=/^([a-z]+:)?\/\//i;return{resolve:(e,t,a=!1)=>{(e=>i.test(e))(e)||(e.startsWith('/')||(e='/'+e),e=s+e);let r=e.indexOf('?')>-1?'&':'?';return a&&(e+=r+'lowLat=1',r='&'),t&&(e+=r+'_rnd='+Math.floor(999999999*Math.random())),e}}}function ve(t,s,i,a){const r=window.XMLHttpRequest;let o,n,d,u,h,c=!1,l=0,p=!1,m='arraybuffer',S=7e3,f=2e3,b=()=>{if(c)return;e.assertNonNullable(u);const t=be(u);let s;if(t<f)return s=f-t,void setTimeout(b,s);f*=2,f>S&&(f=S),n&&n.abort(),n=new r,v()};const g=()=>{if(!c){if(--l>=0)return b(),void(a&&a());c=!0,h&&h(),i&&i()}},v=()=>{u=fe(),n=new r,n.open('get',t);let i,a=0,l=0;const S=()=>(e.assertNonNullable(u),Math.max(u,Math.max(i||0,l||0)));if(o&&n.addEventListener('progress',(e=>{const t=fe();o.updateChunk&&e.loaded>a&&(o.updateChunk(S(),e.loaded-a),a=e.loaded,i=t)})),d&&(n.timeout=d,n.addEventListener('timeout',(()=>g()))),n.addEventListener('load',(()=>{if(c)return;e.assertNonNullable(n);const t=n.status;if(t>=200&&t<300){if(n.response.byteLength&&o){const e=n.response.byteLength-a;e&&o.updateChunk&&o.updateChunk(S(),e)}h&&h(),n&&s(n.response)}else g()})),n.addEventListener('error',(()=>{g()})),p){const t=()=>{e.assertNonNullable(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(l=fe(),n.removeEventListener('readystatechange',t))};n.addEventListener('readystatechange',t)}return n.responseType=m,n.send(),y},y={withBitrateReporting:e=>(o=e,y),withParallel:e=>(p=e,y),withJSONResponse:()=>(m='json',y),withRetryCount:e=>(l=e,y),withRetryInterval:(t,s)=>(e.isNonNullable(t)&&(f=t),e.isNonNullable(s)&&(S=s),y),withTimeout:e=>(d=e,y),withFinally:e=>(h=e,y),send:v,abort:()=>{n&&(n.abort(),n=void 0),c=!0,h&&h()}};return y}class ye{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<.1*this.currentRate?t=.8:e<.5*this.currentRate?t=.5:e<.7*this.currentRate&&(t=.3)),e=Math.max(1,Math.min(e,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end&&(this._doMergeIntervals(e,t),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let s=0,i=0;for(;this.intervals.length>0;){const e=this.intervals[0];if(e.end<=t)s+=e.end-e.start,i+=e.bytes,this.intervals.splice(0,1);else{if(e.start>=t)break;{const a=t-e.start,r=e.end-e.start;s+=a;const o=e.bytes*a/r;i+=o,e.start=t,e.bytes-=o}}}if(i>0&&s>0){const a=8*i/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>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 Te{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:'warn'}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=fe(),i=s=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=s,e._errorCB?e._errorCB(s):(this.limitCompleteCount(),this.completeRequests[t]=e)};e._request=ve(t,(i=>{e._complete=1,e._responseData=i,e._downloadTime=fe()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(i,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)}),(()=>i('error')),(()=>{e._retry=1,e._retryCB&&e._retryCB()})),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{e._finallyCB&&e._finallyCB()})),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(s>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),s),!1)}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(!e)return;this.activeRequests[e]||this.completeRequests[e]||(this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e))}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach((e=>{e&&e._request&&e._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,i){const a={};return a.send=()=>{const r=this.activeRequests[e]||this.completeRequests[e];if(r)r._cb=t,r._errorCB=s,r._retryCB=i,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(e),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${e}`);else{const t=this.pendingQueue.indexOf(e);-1!==t&&this.pendingQueue.splice(t,1),this.logger(`Request not prefetched, starting new request, url=${e}${-1===t?'':'; removed pending'}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=i,a.abort=function(){a.request&&a.request.abort()},a.withFinally=e=>(a._finallyCB=e,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}class Ee{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new ye(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ge(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e)return void this._switchToQuality(t)}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ge(e),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return 0!==s&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:'buffering',isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener('error',(s=>{this.destroyed||(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:'error',type:'media'}))})),e.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),e.pause(),this.videoPlayStarted=!1}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),e.addEventListener('playing',(()=>{t('playing')})),e.addEventListener('stalled',(()=>this._fixupStall())),e.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let i;0!==s&&(i=t.buffered.start(s-1),t.currentTime<i&&(e('Fixup stall'),t.currentTime=i))}_selectQuality(e){const{videoElement:t}=this.params;let s,i,a;const r=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let t=0;t<this.manifest.length;++t)a=this.manifest[t],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<e&&r>Math.min(a.video.height,a.video.width)?(!i||a.bitrate>i.bitrate)&&(i=a):(!s||s.bitrate>a.bitrate)&&(s=a));return i||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||e.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,s){const{logger:i,videoElement:a,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{e.assertNonNullable(this.mediaSource),this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],s()})),this.videoPlayStarted=!1,a.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const o=()=>{!function(e,t,s){const i=(...a)=>{s.apply(null,a),e.removeEventListener(t,i)};e.addEventListener(t,i)}(a,'progress',(()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),r({name:'playing'})):o()}))};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Te(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(e,(()=>this._switchToQuality(e)))}_representation(t){const{logger:s,videoElement:i,playerCallback:a}=this.params;let r=!1,o=null,n=null,d=null,u=null,h=!1;const c=()=>{const e=r&&(!h||h===this.rep);return e||s('Not running!'),e},l=(e,t,s)=>{d&&d.abort(),d=ve(this.urlResolver.resolve(e,!1),t,s,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{d=null})).send()},p=(t,s,i)=>{e.assertNonNullable(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),s,i,(()=>this._retryCallback())).withFinally((()=>{n=null})).send()},m=e=>{const t=i.playbackRate;i.playbackRate!==e&&(s(`Playback rate switch: ${t}=>${e}`),i.playbackRate=e)},S=e=>{this.lowLatency=e,s(`lowLatency changed to ${e}`),f()},f=()=>{if(this.lowLatency){let e=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const t=fe()-6e4;let i=0;for(let s=0;s<this.bufferStates.length;s++){const a=this.bufferStates[s];e=Math.min(e,a.buf),a.ts<t&&i++}this.bufferStates.splice(0,i),s(`update playback rate; minBuffer=${e} drop=${i} jitter=${this.sourceJitter}`);let a=e-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=t=>{let i;const r=()=>i&&i.start?i.start.length:0,o=e=>i.start[e]/1e3,n=e=>i.dur[e]/1e3,d=e=>i.fragIndex+e,h=(e,t)=>({chunkIdx:d(e),startTS:o(e),dur:n(e),discontinuity:t}),l=()=>{let e=0;if(i&&i.dur){let t=Math.max(this.sourceJitter,1);for(this.lowLatency||(t+=2),e=i.dur.length-1;e>=0&&(t-=i.dur[e]/1e3,!(t<=0));--e);}return h(e,!0)},p=(e,t,s)=>{u&&u.abort(),u=ve(this.urlResolver.resolve(e,!0,this.lowLatency),t,s,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(s,n)=>{p(t,(t=>{if(!c())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&S(d);let u=0;for(let e=0;e<i.dur.length;++e)u+=i.dur[e];u>0&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,s((t=>{const s=r();if(!(s<=0)){if(e.isNonNullable(t))for(let e=0;e<s;e++)if(o(e)>t)return h(e);return l()}})(n))}),(()=>this._handleNetworkError()))},nextChunk:e=>{const t=r(),a=e?e.chunkIdx+1:0,o=a-i.fragIndex;if(!(t<=0)){if(!e||o<0||o-t>10)return s(`Resync: offset=${o} bChunks=${t} chunk=`+JSON.stringify(e)),l();if(!(o>=t))return h(a-i.fragIndex,!1)}}}},g=()=>{r=!1,n&&n.abort(),d&&d.abort(),u&&u.abort(),e.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:s=>{const{videoElement:i,logger:a}=this.params;let n,d,h,m,S,v,y,T=b(t.jidxUrl),E=0;const k=()=>{S&&(clearTimeout(S),S=void 0);const e=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),t=E+e,s=fe(),i=Math.min(1e4,t-s);E=s;const a=()=>{u||c()&&T.seek((()=>{c()&&(E=fe(),$(),k())}))};i>0?S=window.setTimeout((()=>{this.paused?k():a()}),i):a()},$=()=>{let e;for(;e=T.nextChunk(m);)m=e,N(e);const s=T.nextChunk(h);if(s){if(h&&s.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?k():(g(),this._initPlayerWith(t)));x(s)}else k()},P=(e,t)=>{if(!c()||!this.sourceBuffer)return;let s,r,o;const n=s=>{window.setTimeout((()=>{c()&&P(e,t)}),s)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const d=fe(),u=i.currentTime;!this.paused&&i.buffered.length>1&&v===u&&d-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),v!==u&&(v=u,y=d);const h=this._getBufferSizeSec();if(h>30)a(`Buffered ${h} seconds; delaying appendBuffer`),n(2e3);else try{this.sourceBuffer.appendBuffer(e),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),f(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),t&&t()}catch(e){if('QuotaExceededError'!==e.name)throw e;a('QuotaExceededError; delaying appendBuffer'),o=this.sourceBuffer.buffered.length,0!==o&&(s=this.sourceBuffer.buffered.start(0),r=u,r-s>4&&this.sourceBuffer.remove(s,r-3)),n(1e3)}}},w=()=>{d&&n&&(a([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),P(d,(function(){d=null,$()})))},A=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),x=e=>{c()&&p(A(e),((t,s)=>{if(c()){if(s/=1e3,d=t,h=e,o=e.startTS,s){const t=Math.min(10,e.dur/s);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*t:t}w()}}),(()=>this._handleNetworkError()))},N=t=>{c()&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(t),!1)))},_=e=>{c()&&(t.cachedHeader=e,P(e,(()=>{n=!0,w()})))};r=!0,T.seek((t=>{c()&&(E=fe(),t?(m=t,!e.isNullable(s)||t.startTS>s?x(t):(h=t,$())):k())}),s),t.cachedHeader?_(t.cachedHeader):l(t.headerUrl,_,(()=>this._handleNetworkError()))},stop:g,getTimestampSec:()=>o},h}_switchToQuality(t){const{logger:s,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),e.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),s(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,e.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return e.isNonNullable(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=t=>{if(!this.autoQuality)return;let s,i,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&t<this.bitrate&&(i=this._getBufferSizeSec(),a=t/this.bitrate,i>10&&a>.8||i>15&&a>.5||i>20&&a>.3)?e(`Not switching: buffer=${Math.floor(i)}; bitrate=${this.bitrate}; newRate=${Math.floor(t)}`):(s=this._selectQuality(t),s?this._switchToQuality(s):e(`Could not find quality by bitrate ${t}`))},i=(()=>({updateChunk:(e,s)=>{const i=fe();if(this.chunkRateEstimator.addInterval(e,i,s)){const a=this.chunkRateEstimator.getBitRate();return t({name:'bandwidth',size:s,duration:i-e,speed:a}),!0}},get:()=>{const e=this.chunkRateEstimator.getBitRate();return e?.85*e:0}}))();let a,r=-1/0,o=!0;const n=()=>{let e=i.get();if(e&&a&&this.autoQuality){if(o&&e>a&&be(r)<3e4)return;s(e)}o=this.autoQuality};return{updateChunk:(e,t)=>{const s=i.updateChunk(e,t);return s&&n(),s},notifySwitch:e=>{const t=fe();e<a&&(r=t),a=e}}}_fetchManifest(e,t,s){this.manifestRequest=ve(this.urlResolver.resolve(e,!0),t,s,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(e){const{videoElement:t}=this.params;Se(t).then((t=>{t||e?.()}))}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params;this.manifest=(e=>{const t=[];return e?.length?(e.forEach(((e,s)=>{e.video&&i.canPlayType(e.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(e.codecs)&&(e.index=s,t.push(e))})),t.sort((function(e,t){return e.video&&t.video?t.video.height-e.video.height:t.bitrate-e.bitrate})),t):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:'manifest',manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(e,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))}),(()=>this._refetchManifest(e)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var ke;!function(e){e.STOPPED='stopped',e.MANIFEST_READY='manifest_ready',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ke||(ke={}));const $e=[ke.PAUSED,ke.PLAYING,ke.READY],Pe=[ke.PAUSED,ke.PLAYING,ke.READY];class we{subscription=new e.Subscription;video;videoState=new k(ke.STOPPED);dash;representations$=new e.ValueSubject([]);textTracksManager=new Y;maxSeekBackTime$=new e.ValueSubject(1/0);zeroTime$=new e.ValueSubject(void 0);liveOffset=new z;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const s=e=>{t.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:e})};e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>({transition:e,type:'start'})))),this.videoState.stateChangeEnded$.pipe(e.map((e=>({transition:e,type:'end'}))))).subscribe((({transition:e,type:t})=>{this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.video=Q(t.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Z(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ke.READY&&this.videoState.setState(ke.READY)}),s)).add(i.pause$.subscribe((()=>{this.videoState.setState(ke.PAUSED)}),s)).add(i.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===h.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(ke.PLAYING)}),s)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map((e=>-e/1e3))).subscribe(this.params.output.duration$)).add(e.combine({zeroTime:this.zeroTime$.pipe(e.filter(e.isNonNullable)),position:i.timeUpdate$}).subscribe((({zeroTime:e,position:t})=>this.params.output.liveTime$.next(e+1e3*t)),s)).add(H(this.video,this.params.desiredState.isLooped,s)).add(j(this.video,this.params.desiredState.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(this.params.output.volume$,s)).add(X(this.video).subscribe(this.params.output.firstBytesEvent$)).add(W(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:e}})=>{const t=e&&b[e].height;this.dash.setMaxAutoQuality(t)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case ke.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case ke.MANIFEST_READY:case ke.READY:break;case ke.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case ke.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return e.assertNever(t.to)}}),s)).add(e.merge(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekState.stateChangeEnded$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Ee({videoElement:this.video,config:{CHUNK_DURATION:this.params.config.chunkDuration,BUFFER_OPTIMAL_DURATION:this.params.config.optimalBufferDuration,MAX_PARALLEL_REQUESTS:this.params.config.maxParallelRequests},playerCallback:this._dashCb,logger:e=>{this.params.dependencies.logger.log({message:String(e),component:'LiveDashPlayer'})}});return e.pause(),e}prepare(){const t=this.representations$.getValue(),s=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&e.isNonNullable(s)?s:ne(t.map((({track:e})=>e)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.id,r=t.find((({track:e})=>e.id===a))?.representation;e.assertNonNullable(r),this.dash.startPlay(r,i),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(i)}setVideoTrack(t){const s=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;e.assertNonNullable(s),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.dash.reinit(S(this.params.source.url,s))}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,s=[];for(const t of e){const e=t.name??t.index.toString(10),i=me(t.name)??T(t.video),a=t.bitrate/1e3,r={...t.video};if(!i)continue;const o={id:e,quality:i,bitrate:a,size:r};s.push({track:o,representation:t})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map((({track:e})=>e))),this.videoState.getTransition()?.to===ke.MANIFEST_READY&&this.videoState.setState(ke.MANIFEST_READY);break}case'qualitySwitch':{const s=t.quality,i=this.representations$.getValue().find((({representation:e})=>e===s))?.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),e.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:s}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,s);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==exports.PlaybackState.STOPPED){if(!s){if(Pe.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;e.isNonNullable(t)&&this.setVideoTrack(t);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if(a?.to!==exports.PlaybackState.PAUSED&&r.state===h.Requested&&$e.includes(t))this.seek(r.position-this.liveOffset.getTotalPausedTime());else switch(t){case ke.STOPPED:return this.videoState.startTransitionTo(ke.MANIFEST_READY),void this.dash.attachSource(S(this.params.source.url));case ke.MANIFEST_READY:this.videoState.startTransitionTo(ke.READY),this.prepare();break;case ke.READY:return void(i===exports.PlaybackState.PAUSED?this.videoState.setState(ke.PAUSED):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ke.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(ke.PAUSED)}))));case ke.PLAYING:return void(i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(ke.PAUSED),this.liveOffset.pause(),this.dash.pause()));case ke.PAUSED:return void(i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ke.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(ke.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return e.assertNever(t)}}}else t!==ke.STOPPED&&(this.videoState.startTransitionTo(ke.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(ke.STOPPED))}}var Ae=e=>{const t=e.get('X-Delivery-Type'),s=e.get('X-Reused');return{type:null===t?exports.HttpConnectionType.HTTP1:t??void 0,reused:null===s?void 0:{1:!0,0:!1}[s]??void 0}},xe=(e,t)=>{let s=0;for(let i=0;i<e.length;i++){const a=1e3*e.start(i),r=1e3*e.end(i);a<=t&&t<=r&&(s=r)}return Math.max(s-t,0)};class Ne{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,a,r){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(e.assertNonNullable(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((e=>e.split(':').map((e=>e.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(e){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(e)}`,e),e}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('XHR2Failover','XHR failed, retrying failover host');else{let e;this._failoverIndex>=this._failoverHosts.length?(e=this._url,this._failoverIndex=0):(e=this._url.replace((e=>{const t=document.createElement('a');return t.href=e,t.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',e,!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 _e{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(e){if('QuotaExceededError'!==e.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',e),e;{this._isFull=!0;const e=this._sourceBuffer.buffered;let t=0;for(let s=0,i=e.length;s<i;s++)t+=e.end(s)-e.start(s);t&&(this._maxBufferDuration=Math.round(t))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,a,r,o){this.abort((()=>{let n=0;const d=Date.now();let u=0,h=0,c=0;const l=e=>{i(_e._str2ua(e.substr(n))),n=e.length};let p=e.baseURL+'&bytes='+t+'-'+s;this._params.requestQuic&&(p=F(p)),this._lastXhr=new Ne(p,e.failoverHosts,(e=>{this._lastXhr=void 0,l(e);const t=Date.now()-d;this._params.onBandwidthChange({size:e.length,duration:t,speed:8*e.length/(t/1e3)}),this._onDashCallback('loading',{size:e.length,done:!0}),a?.()}),(e=>{if(e.length-n>o&&l(e),0===h)return void(h=Date.now());c=e.length-u;const t=Date.now()-h;c>=102400&&t>=1e3&&(this._params.onBandwidthChange({size:c,duration:t,speed:8*c/(t/1e3)}),c=0,u=e.length,h=Date.now()),this._onDashCallback('loading',{size:e.length,done:!1})}),r,((e,t,s)=>this._params.onError(e,t,s)))}))}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),e?.()}))}))}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(e){throw this._params.onError('SourceBuffer','Source Buffer update error',e),e}};return this._sourceBuffer.addEventListener('updateend',t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener('updateend',e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=_e._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class De{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=(e,t)=>{const s=e?parseFloat(e.replace(',','.')):NaN;return(isNaN(s)?0:s)*t},s=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(e),i='-'===s?.[1]?-1:1;t(s?.[2],i),t(s?.[3],i),t(s?.[4],i),t(s?.[5],i);return 3600*t(s?.[6],i)+60*t(s?.[7],i)+t(s?.[8],i)}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=F(s)),new Ne(s,t,(e=>{this.attachManifest(e,t,(e=>{const t=document.createElement('a');return t.href=e,t.origin})(s))}),void 0,(e=>{this._params.onResponseHeaders(e)}),((e,t,s)=>this._params.onError(e,t,s)))}attachManifest(e,t,s){const i=(new DOMParser).parseFromString(e,'text/xml').documentElement,a=(e,t)=>{const s=e.attributes.getNamedItem(t);return s?s.value:null};this._duration=this._parseDurationFromISO8601(String(a(i,'mediaPresentationDuration')));const r=[],o=[];Array.prototype.forEach.call(i.getElementsByTagName('Representation'),(e=>{const i=e.getElementsByTagName('SegmentBase')[0],n=i&&a(i,'indexRange').split('-'),d=i&&i.getElementsByTagName('Initialization')[0],u=d&&a(d,'range').split('-');if(!u||!n){const t=e.parentElement;if('text'===t?.getAttribute('contentType')){const i=e.getAttribute('id')??void 0,a=(s?s+'/':'')+e.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=t.getAttribute('lang')??void 0;a&&o.push({id:i,url:a,language:r})}return}const h=Number(e.attributes.getNamedItem('bandwidth')?.value),c=(s?s+'/':'')+e.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=e.attributes.getNamedItem('frameRate')?.value??void 0;l=p?ee(p):void 0,r.push({width:Number(e.attributes.getNamedItem('width')?.value),height:Number(e.attributes.getNamedItem('height')?.value),bandwidth:h,baseURL:c,failoverHosts:t,indexFrom:Number(n[0]),indexTo:Number(n[1]),initFrom:Number(u[0]),initTo:Number(u[1]),codecs:e.attributes.getNamedItem('codecs')?.value??void 0,mimeType:e.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*h/8,bufferLength:.1,name:e.attributes.getNamedItem('okQuality')?.value??void 0,id:e.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,o.forEach((({id:e,language:t,url:s})=>{const i=document.createElement('track');i.setAttribute('src',s),e&&i.setAttribute('id',e),t&&i.setAttribute('srclang',t),this._video.appendChild(i)})),this._representations.sort(((e,t)=>t.bandwidth-e.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(e,t){if(e===this._currentRepresentation)return void(t&&t());if(e.refs)return void this._stream.abort((()=>{this._stream.append(e.initMessage,t)}));const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,(s=>{let i=e.initTo-e.initFrom+1;if(!s.byteLength)return void this._params.onError('EmptyResponse','Empty response');e.initMessage=new Uint8Array(s.buffer,0,i);const a=new DataView(s.buffer);i+=12;const r=a.getUint32(i+4,!1);i+=8;let o=a.getUint32(i,!1),n=a.getUint32(i+4,!1)+(e.indexTo+1);i+=8;const d=a.getUint16(i+2,!1);i+=4,e.refs=[];for(let t=0;t<d;t+=1){const t=n+(2147483647&a.getUint32(i,!1)),s=o+a.getUint32(i+4,!1);i+=12,e.refs.push({fromTime:o/r,toTime:s/r,fromOffset:n,toOffset:t-1}),n=t,o=s}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)}),void 0,(e=>{this._params.onResponseHeaders(e),this._params.onIdxRequestPing(Date.now()-s)}),e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const s=new t;let i,a;const r=()=>{const t=this._findRef(this._video.currentTime);if(!t||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 e=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),e)}const s=this._appendVector[String(t.fromTime)];let r;s!==i&&(i=s,this._params.onRepresentationPlay(s));if(this._findRef(t.toTime)){const t=this._buffer.getByTime(this._video.currentTime);if(!t)return void this._onDashCallback('buffering');r=t.end-this._video.currentTime,r<e.bufferLength&&(this._onDashCallback('buffering'),a!==t.end&&(a=t.end,window.setTimeout((()=>{try{const e=this._buffer.getNextWithGap(t);e&&(this._video.currentTime=e.start)}catch(e){throw this._params.onError('GapSyncError',`Seek Error ${String(e)}`,e),e}}),1e3*r)))}},o=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(e){throw this._params.onError('LoopError',`Dash Loop exception ${String(e)}`,e),e}o()}),250)},n=()=>{if(!this._stream)try{const t=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new _e({mediaSource:s,sourceBuffer:t,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(e){throw this._params.onError('DashSourceOpen',`Source open exception ${String(e)}`,e),e}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener('sourceopen',n),s.removeEventListener('webkitsourceopen',n)};s.addEventListener('sourceopen',n,!1),s.addEventListener('webkitsourceopen',n,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener('waiting',(()=>{const e=this._video&&this._video.played.length;e&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(e-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(e,t,s=!1,i=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,(()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const e=this._findRef(this._video.currentTime),s=Math.abs(this._video.currentTime-t),r=i||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===e||s<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,((e,t)=>this._stream.append(e,t)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(e=>this._params.onResponseHeaders(e)),e.bufferSize)}}))}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i)return void(this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime));const a=.1;if(i.toTime<s.end+a){const t=this._findRef(i.toTime);t&&t.toTime<s.end+a?(this._buffer.smartRemove(i.fromTime-a,t.toTime+a,((e,t)=>this._stream.remove(e,t))),this._loadRef(e,t.toTime)):(this._buffer.smartRemove(i.fromTime-a,i.toTime+a,((e,t)=>this._stream.remove(e,t))),this._loadRef(e,i.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!e.isNullable(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&0===t.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let i=0;i<t.length;i++){const a=t[i];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const s=t[t.length-1];if(e>s.toTime)return s}return s}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const s=t[t.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),i=this._video.buffered.end(t);if(e>s&&e<i)return Math.round(10*i)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Re;!function(e){e.STOPPED='stopped',e.MANIFEST_LOADED='manifest-loaded',e.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',e.METADATA_LOADED='metadata-loaded',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Re||(Re={}));const Ie=[Re.PAUSED,Re.PLAYING];class Ce{videoState=new k(Re.STOPPED);subscription=new e.Subscription;video;buffer;dash;representations$=new e.ValueSubject([]);currentRepresentation$=new e.ValueSubject(void 0);params;textTracksManager=new Y;elementSize$=new e.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new e.Subject,responseHeaders$:new e.Subject,manifestReady$:new e.Subject,representationPlay$:new e.Subject,error$:new e.Subject};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>({transition:e,type:'start'})))),this.videoState.stateChangeEnded$.pipe(e.map((e=>({transition:e,type:'end'}))))).subscribe((({transition:e,type:t})=>{this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.video=Q(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new J(this.video),this.dash=new De({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:e=>this.dashLiteEvents.idxRequestPing$.next(e),onResponseHeaders:e=>this.dashLiteEvents.responseHeaders$.next(e),onManifestReady:e=>this.dashLiteEvents.manifestReady$.next(e),onRepresentationPlay:e=>this.dashLiteEvents.representationPlay$.next(e),onBandwidthChange:e=>this.params.dependencies.throughputEstimator.addRawSpeed(e.size,e.duration),onError:(e,t,s)=>{this.log({message:`[DashLite error], ${e}`}),this.dashLiteEvents.error$.next({id:e,message:t,thrown:s})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},a=()=>{const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.autoVideoTrackSwitching.getTransition();return t?t.to:e},r=Z(this.video),o=(e,t)=>this.subscription.add(e.subscribe(t,i));o(r.timeUpdate$,t.position$),o(r.durationChange$,t.duration$),o(r.ended$,t.endedEvent$),o(r.looped$,t.loopedEvent$),o(r.error$,t.error$),o(r.isBuffering$,t.isBuffering$),o(r.firstFrame$,t.firstFrameEvent$),this.subscription.add(r.seeking$.subscribe((()=>{e.isNullable(this.params.desiredState.seekState.getState().state!==h.Applying)&&(this.videoState.getState()===Re.PLAYING||this.videoState.getState()===Re.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(H(this.video,s.isLooped,i)),this.subscription.add(j(this.video,s.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,s,t),o(ue(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Re.READY&&this.videoState.setState(Re.READY)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Re.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Re.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),i)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Re.METADATA_LOADED)}),i)).add(r.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(e.map((({id:e,message:t,thrown:s})=>({id:`DashLite_${e}`,message:t,thrown:s})))).subscribe(this.params.output.error$)).add(e.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$,e.fromEvent(this.video,'progress')).pipe(e.map((()=>{const t=this.currentRepresentation$.getValue(),s=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),r=this.params.desiredState.videoTrack.getState(),o=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),n=this.elementSize$.getValue(),d=a();let u;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&e.isNonNullable(r))u=r;else{const e=xe(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);u=ne(s.map((({track:e})=>e)),{container:n,throughput:o,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:i,currentRepresentation:t})?.id}return e.isNonNullable(u)?s.find((({track:e})=>e.id===u))?.representation:void 0})),e.filterChanged()).subscribe(this.currentRepresentation$,i)).add(e.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(e.filter((e=>e.to===Re.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(e.filter(e.isNonNullable))}).pipe(e.once()).subscribe((()=>this.videoState.setState(Re.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(e.filter(e.isNonNullable),e.filterChanged(((e,t)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?e.height<=t.height:e===t))).subscribe((e=>{const t=xe(this.video.buffered,1e3*this.video.currentTime),s=Math.min(t/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||s<=.5||!a())&&(this.dash.setQualityByRepresentation(e,!0),this.params.output.hostname$.next(de(e.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((e=>{const{type:t,reused:s}=Ae(e);this.params.output.httpConnectionType$.next(t),this.params.output.httpConnectionReused$.next(s)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(e.once()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((e=>this.params.dependencies.throughputEstimator.addRawRtt(e)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(e.filter(e.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return e.assertNever(t)}}handleManifestReady=e=>{const t=[];for(const s of e){const e=s.name??s.id??s.height.toString(10),i=(s.name&&me(s.name))??T(s),a=s.bandwidth/1e3,r={width:s.width,height:s.height},o=s.fps;if(!i)continue;const n={id:e,quality:i,bitrate:a,size:r,fps:o};t.push({track:n,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map((({track:e})=>e))),this.videoState.setState(Re.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find((({representation:t})=>t===e))?.track;if(t){this.params.output.currentVideoTrack$.next(t);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return e.assertNonNullable(t,'Can\'t select representation. something went wrong'),t};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(Re.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==exports.PlaybackState.STOPPED){if(!s)switch(a?.to!==exports.PlaybackState.PAUSED&&r.state===h.Requested&&Ie.includes(t)&&this.seek(r.position,r.forcePrecise),t){case Re.STOPPED:return this.videoState.startTransitionTo(Re.MANIFEST_LOADED),void this.prepare();case Re.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Re.INITIAL_REPRESENTATION_SELECTED);case Re.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Re.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Re.METADATA_LOADED:return this.videoState.startTransitionTo(Re.READY),void this.dash.updateRefsForCurrentTime();case Re.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Re.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Re.PLAYING),this.playIfAllowed()));case Re.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Re.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Re.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Re.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==Re.STOPPED&&(this.videoState.startTransitionTo(Re.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(Re.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))}}var Le,Be,Oe,Ve;!function(e){e.VIDEO='video',e.AUDIO='audio',e.TEXT='text'}(Le||(Le={})),function(e){e.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',e.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(Be||(Be={})),function(e){e.NONE='none',e.DOWNLOADING='downloading',e.DOWNLOADED='downloaded',e.PARTIALLY_FED='partially_fed',e.FED='fed'}(Oe||(Oe={})),function(e){e.MP4='mp4',e.WEBM='webm'}(Ve||(Ve={}));class Me{bufferFull$=new e.Subject;error$=new e.Subject;buffer;queue=[];currentTask=null;constructor(e){this.buffer=e,this.buffer.addEventListener('updateend',this.onUpdateEnd)}async append(e,t){return(!t||!t.aborted)&&new Promise((s=>{const i={operation:'append',data:e,signal:t,callback:s};this.queue.push(i),this.pull()}))}async remove(e,t,s){return(!s||!s.aborted)&&new Promise((i=>{const a={operation:'remove',from:e,to:t,signal:s,callback:i};this.queue.unshift(a),this.pull()}))}destroy(){this.buffer.removeEventListener('updateend',this.onUpdateEnd)}onUpdateEnd=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:'BufferTaskQueue',message:'Buffer appending or removal failed',thrown:e})}};pull(){if(this.buffer.updating||this.currentTask)return;const e=this.queue.shift();if(e){if(e.signal?.aborted)return e.callback(!1),void this.pull();this.currentTask=e;try{this.execute(this.currentTask)}catch(e){this.currentTask.callback(!1),this.currentTask=null}}}execute(t){const{operation:s}=t;switch(s){case'append':try{this.buffer.appendBuffer(t.data)}catch(e){throw e instanceof DOMException&&'QuotaExceededError'===e.name&&this.bufferFull$.next(t.data.byteLength),e}break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;default:e.assertNever(s)}}}var Fe;!function(e){e[e.HEADER=0]='HEADER',e[e.PARAM=1]='PARAM'}(Fe||(Fe={}));class Ue{throughputEstimator;requestQuic;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);abortAllController=new I;subscription=new e.Subscription;constructor({throughputEstimator:e,requestQuic:t}){this.throughputEstimator=e,this.requestQuic=t}onHeadersReceived(e){const{type:t,reused:s}=Ae(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=e.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=F(t));const s=yield R(t,{signal:this.abortAllController.signal}).catch(qe);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetchRange=e.abortable(this.abortAllController.signal,async function*(t,s,i,{method:a=Fe.HEADER,onProgress:r,signal:o}={}){let n=t;const d=new Headers;switch(a){case Fe.HEADER:d.append('Range',`${s}-${i}`);break;case Fe.PARAM:{const e=new URL(n,location.href);e.searchParams.append('bytes',`${s}-${i}`),n=e.toString();break}default:e.assertNever(a)}this.requestQuic&&(n=F(n));let u=this.abortAllController.signal;if(o){const t=new I;this.subscription.add(e.merge(e.fromEvent(this.abortAllController.signal,'abort'),e.fromEvent(o,'abort')).subscribe((()=>{t.abort()}))),(this.abortAllController.signal.aborted||o.aborted)&&t.abort(),u=t.signal}const h=e.now(),c=yield R(n,{headers:d,signal:u}).catch(qe);if(this.throughputEstimator?.addRawRtt(e.now()-h),!c)return null;if(!c.ok||!c.body)return Promise.reject(new Error(`Fetch error ${c.status}: ${c.statusText}`));this.onHeadersReceived(c.headers);const[l,p]=c.body.tee(),m=l.getReader();this.throughputEstimator?.trackStream(p);const S=parseInt(c.headers.get('Content-Length')??'',10);let f=0;const b=new ArrayBuffer(S),g=new Uint8Array(b),v=new DataView(b);let y=!1;const T=e=>{y=!0,qe(e)},E=e.abortable(u,async function*({done:t,value:s}){0===f&&this.lastRequestFirstBytes$.next(e.now()-h),t?r?.(v,f):s&&(g.set(s,f),f+=s.byteLength,r?.(v,f),yield m?.read().then(E,T))}.bind(this));return yield m?.read().then(E,T),y?null:b}.bind(this));fetchRepresentation=e.abortable(this.abortAllController.signal,async function*(e,t,s=0){const{from:i,to:a}=e.initRange;let r,o,n=i,d=a,u=!1;e.indexRange&&(r=e.indexRange.from,o=e.indexRange.to,u=a+1===r,u&&(n=Math.min(r,i),d=Math.max(o,a))),n=Math.min(n,0),d+=s;const h=yield this.fetchRange(e.url,n,d,{method:Fe.PARAM});if(!h)return null;const c=new DataView(h,i-n,a-n+1);if(!t.validateData(c))throw new Error('Invalid media file');const l=t.parseInit(c);let p;if(u&&void 0!==r&&void 0!==o)p=new DataView(h,r-n,o-r+1);else{const s=t.getIndexRange(l);if(s){const t=yield this.fetchRange(e.url,s.from,s.to,{method:Fe.PARAM});if(!t)return null;p=new DataView(t)}}if(!p)throw new ReferenceError('No way to load representation index');const m=t.parseSegments(p,l);return{dataView:new DataView(h),segments:m}}.bind(this));destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const qe=e=>{if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e},He=new TextDecoder('ascii'),je=e=>{let t=0,s=e.getUint32(t);t+=4;const i=new DataView(e.buffer,e.byteOffset+t,4),a=He.decode(i);t+=4,0===s?s=1/0:1===s&&(t+=8,s=1/0);const r=Math.min(s,e.byteLength)-t;return{id:a,size:s,contents:new DataView(e.buffer,e.byteOffset+t,r)}},Ge={validateData:e=>'ftyp'===He.decode(new DataView(e.buffer,e.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:e=>{const t=je(e),s=[];let i=0;const a=()=>{const e=t.contents.getUint32(i);return i+=4,e};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),o=a(),n=a(),d=255&a();let u=o/r*1e3,h=e.byteOffset+e.byteLength+n;for(let e=0;e<d;e++){const e=a(),t=e>>>31,i=e<<1>>>1,o=a();if(a(),0!==t)throw new Error('Unsupported multilevel sidx');const n=o/r*1e3;s.push({status:Oe.NONE,time:{from:u,to:u+n},byte:{from:h,to:h+i-1}}),u+=n,h+=i}return s},parseFeedableSegmentChunk:e=>{let t=0,s=!1,i=!1;for(;t<=e.byteLength&&!s;){const a=new DataView(e.buffer,e.byteOffset+t);try{const s=je(a);if(i||='mdat'===s.id,!(t+s.size<=e.byteLength))break;t+=s.size}catch(e){s=!0}}return t>0&&t<=e.byteLength&&i?new DataView(e.buffer,e.byteOffset,t):null}};var Ye,Qe;!function(e){e[e.EBML=440786851]='EBML',e[e.EBMLVersion=17030]='EBMLVersion',e[e.EBMLReadVersion=17143]='EBMLReadVersion',e[e.EBMLMaxIDLength=17138]='EBMLMaxIDLength',e[e.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',e[e.DocType=17026]='DocType',e[e.DocTypeVersion=17031]='DocTypeVersion',e[e.DocTypeReadVersion=17029]='DocTypeReadVersion',e[e.Void=236]='Void',e[e.Segment=408125543]='Segment',e[e.SeekHead=290298740]='SeekHead',e[e.Seek=19899]='Seek',e[e.SeekID=21419]='SeekID',e[e.SeekPosition=21420]='SeekPosition',e[e.Info=357149030]='Info',e[e.TimestampScale=2807729]='TimestampScale',e[e.Duration=17545]='Duration',e[e.Tracks=374648427]='Tracks',e[e.Chapters=272869232]='Chapters',e[e.Cluster=524531317]='Cluster',e[e.Timestamp=231]='Timestamp',e[e.SilentTracks=22612]='SilentTracks',e[e.SilentTrackNumber=22743]='SilentTrackNumber',e[e.Position=167]='Position',e[e.PrevSize=171]='PrevSize',e[e.SimpleBlock=163]='SimpleBlock',e[e.BlockGroup=160]='BlockGroup',e[e.EncryptedBlock=175]='EncryptedBlock',e[e.Attachments=423732329]='Attachments',e[e.Tags=307544935]='Tags',e[e.Cues=475249515]='Cues',e[e.CuePoint=187]='CuePoint',e[e.CueTime=179]='CueTime',e[e.CueTrackPositions=183]='CueTrackPositions',e[e.CueTrack=247]='CueTrack',e[e.CueClusterPosition=241]='CueClusterPosition',e[e.CueRelativePosition=240]='CueRelativePosition',e[e.CueDuration=178]='CueDuration',e[e.CueBlockNumber=21368]='CueBlockNumber',e[e.CueCodecState=234]='CueCodecState',e[e.CueReference=219]='CueReference',e[e.CueRefTime=150]='CueRefTime'}(Ye||(Ye={})),function(e){e.SignedInteger='int',e.UnsignedInteger='uint',e.Float='float',e.String='string',e.UTF8='utf8',e.Date='date',e.Master='master',e.Binary='binary'}(Qe||(Qe={}));const ze={[Ye.EBML]:{type:Qe.Master},[Ye.EBMLVersion]:{type:Qe.UnsignedInteger},[Ye.EBMLReadVersion]:{type:Qe.UnsignedInteger},[Ye.EBMLMaxIDLength]:{type:Qe.UnsignedInteger},[Ye.EBMLMaxSizeLength]:{type:Qe.UnsignedInteger},[Ye.DocType]:{type:Qe.String},[Ye.DocTypeVersion]:{type:Qe.UnsignedInteger},[Ye.DocTypeReadVersion]:{type:Qe.UnsignedInteger},[Ye.Void]:{type:Qe.Binary},[Ye.Segment]:{type:Qe.Master},[Ye.SeekHead]:{type:Qe.Master},[Ye.Seek]:{type:Qe.Master},[Ye.SeekID]:{type:Qe.Binary},[Ye.SeekPosition]:{type:Qe.UnsignedInteger},[Ye.Info]:{type:Qe.Master},[Ye.TimestampScale]:{type:Qe.UnsignedInteger},[Ye.Duration]:{type:Qe.Float},[Ye.Tracks]:{type:Qe.Master},[Ye.Chapters]:{type:Qe.Master},[Ye.Cluster]:{type:Qe.Master},[Ye.Timestamp]:{type:Qe.UnsignedInteger},[Ye.SilentTracks]:{type:Qe.Master},[Ye.SilentTrackNumber]:{type:Qe.UnsignedInteger},[Ye.Position]:{type:Qe.UnsignedInteger},[Ye.PrevSize]:{type:Qe.UnsignedInteger},[Ye.SimpleBlock]:{type:Qe.Binary},[Ye.BlockGroup]:{type:Qe.Master},[Ye.EncryptedBlock]:{type:Qe.Binary},[Ye.Attachments]:{type:Qe.Master},[Ye.Tags]:{type:Qe.Master},[Ye.Cues]:{type:Qe.Master},[Ye.CuePoint]:{type:Qe.Master},[Ye.CueTime]:{type:Qe.UnsignedInteger},[Ye.CueTrackPositions]:{type:Qe.Master},[Ye.CueTrack]:{type:Qe.UnsignedInteger},[Ye.CueClusterPosition]:{type:Qe.UnsignedInteger},[Ye.CueRelativePosition]:{type:Qe.UnsignedInteger},[Ye.CueDuration]:{type:Qe.UnsignedInteger},[Ye.CueBlockNumber]:{type:Qe.UnsignedInteger},[Ye.CueCodecState]:{type:Qe.UnsignedInteger},[Ye.CueReference]:{type:Qe.Master},[Ye.CueRefTime]:{type:Qe.UnsignedInteger}},We=e=>{const t=e.getUint8(0);let s=0;128&t?s=1:64&t?s=2:32&t?s=3:16&t&&(s=4);const i=Je(e,s),a=i in ze,r=a?ze[i].type:Qe.Binary,o=e.getUint8(s);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 d=new DataView(e.buffer,e.byteOffset+s+1,n-1),u=((o&255>>n)<<8*(n-1))+Je(d),h=s+n;let c;return c=h+u>e.byteLength?new DataView(e.buffer,e.byteOffset+h):new DataView(e.buffer,e.byteOffset+h,u),{tag:a?i:'0x'+i.toString(16).toUpperCase(),type:r,tagHeaderSize:h,tagSize:h+u,value:c,valueSize:u}},Je=(e,t=e.byteLength)=>{switch(t){case 1:return e.getUint8(0);case 2:return e.getUint16(0);case 3:return e.getUint16(0)<<8|e.getUint8(2);case 4:return e.getUint32(0);case 5:return e.getUint32(0)<<8|e.getUint8(4);case 6:return e.getUint32(0)<<16|e.getUint16(4);case 7:return e.getUint32(0)<<32|e.getUint16(4)<<8|e.getUint8(6);case 8:return e.getUint32(0)<<32|e.getUint32(4)}return 0},Ke=(t,s)=>{switch(s){case Qe.SignedInteger:return t.getInt8(0);case Qe.UnsignedInteger:return Je(t);case Qe.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Qe.String:return new TextDecoder('ascii').decode(t);case Qe.UTF8:return new TextDecoder('utf-8').decode(t);case Qe.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Qe.Master:case Qe.Binary:return t;default:e.assertNever(s)}},Xe=(e,t)=>{let s=0;for(;s<e.byteLength;){const i=new DataView(e.buffer,e.byteOffset+s),a=We(i);if(!t(a))return;a.type===Qe.Master&&Xe(a.value,t),s=a.value.byteOffset-e.byteOffset+a.valueSize}},Ze=[Ye.Info,Ye.SeekHead,Ye.Tracks,Ye.Chapters,Ye.Cluster,Ye.Cues,Ye.Attachments,Ye.Tags],et=[Ye.Timestamp,Ye.SilentTracks,Ye.SilentTrackNumber,Ye.Position,Ye.PrevSize,Ye.SimpleBlock,Ye.BlockGroup,Ye.EncryptedBlock],tt={validateData:e=>{if(e.getUint32(0)!==Ye.EBML)return!1;let t,s,i;const a=We(e);return Xe(a.value,(({tag:e,type:a,value:r})=>(e===Ye.EBMLReadVersion?t=Ke(r,a):e===Ye.DocType?s=Ke(r,a):e===Ye.DocTypeReadVersion&&(i=Ke(r,a)),!0))),(void 0===t||t<=1)&&void 0!==s&&'webm'===s&&(void 0===i||i<=2)},parseInit:t=>{let s,i,a,r,o,n,d=!1,u=!1,h=!1;return Xe(t,(({tag:e,type:t,value:c,valueSize:l})=>{if(e===Ye.SeekID){const e=Ke(c,t);n=Je(e)}else e!==Ye.SeekPosition&&(n=void 0);return e===Ye.Segment?(s=c.byteOffset,i=c.byteOffset+l):e===Ye.Info?d=!0:e===Ye.SeekHead?u=!0:e===Ye.TimestampScale?a=Ke(c,t):e===Ye.Duration?r=Ke(c,t):e===Ye.SeekPosition&&n===Ye.Cues?o=Ke(c,t):d&&u&&Ze.includes(e)&&(h=!0),!h})),e.assertNonNullable(s,'Failed to parse webm Segment start'),e.assertNonNullable(i,'Failed to parse webm Segment end'),e.assertNonNullable(r,'Failed to parse webm Segment duration'),a=a??1e6,{segmentStart:Math.round(s/1e9*a*1e3),segmentEnd:Math.round(i/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:o}},getIndexRange:t=>{if(e.isNullable(t.cuesSeekPosition))return;const s=t.segmentStart+t.cuesSeekPosition;return{from:s,to:s+1048576}},parseSegments:(t,s)=>{let i=!1,a=!1;const r=t=>e.isNonNullable(t.time)&&e.isNonNullable(t.position),o=[];let n;return Xe(t,(({tag:e,type:t,value:s})=>{switch(e){case Ye.Cues:i=!0;break;case Ye.CuePoint:n&&r(n)&&o.push(n),n={};break;case Ye.CueTime:n&&(n.time=Ke(s,t));break;case Ye.CueTrackPositions:break;case Ye.CueClusterPosition:n&&(n.position=Ke(s,t));break;default:i&&Ze.includes(e)&&(a=!0)}return!(i&&a)})),n&&r(n)&&o.push(n),o.map(((e,t)=>{const{time:i,position:a}=e,r=o[t+1];return{status:Oe.NONE,time:{from:i,to:r?r.time:s.segmentDuration},byte:{from:s.segmentStart+a,to:r?s.segmentStart+r.position-1:s.segmentEnd-1}}}))},parseFeedableSegmentChunk:e=>{let t=0,s=!1;try{Xe(e,(i=>i.tag===Ye.Cluster?i.tagSize<=e.byteLength?(t=i.tagSize,!1):(t+=i.tagHeaderSize,!0):!!et.includes(i.tag)&&(t+i.tagSize<=e.byteLength&&(t+=i.tagSize,s||=[Ye.SimpleBlock,Ye.BlockGroup,Ye.EncryptedBlock].includes(i.tag)),!0)))}catch(e){}return t>0&&t<=e.byteLength&&s?new DataView(e.buffer,e.byteOffset,t):null}};class st{onLastSegment$=new e.ValueSubject(!1);fullyBuffered$=new e.ValueSubject(!1);playingRepresentation$=new e.ValueSubject(void 0);error$=new e.Subject;gaps=[];subscription=new e.Subscription;kind;container;containerParser;initData;representations;segments;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;segmentDownloadPromise;downloadAbortController=new I;destroyAbortController=new I;getCurrentPosition;loadAllInitsPromise;allInitsLoaded=!1;tuning;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;constructor(t,s,i,a,{fetcher:r,tuning:o,getCurrentPosition:n}){switch(this.fetcher=r,this.tuning=o,this.getCurrentPosition=n,this.container=i,i){case Ve.MP4:this.containerParser=Ge;break;case Ve.WEBM:this.containerParser=tt;break;default:e.assertNever(i)}this.initData=new Map,this.segments=new Map,this.representations=new Map(a.map((e=>[e.id,e]))),this.kind=t,this.mediaSource=s,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}startWith=e.abortable(this.destroyAbortController.signal,async function*(t){const s=this.representations.get(t);e.assertNonNullable(s,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${s.mime}; codecs="${s.codecs}"`),this.sourceBufferTaskQueue=new Me(this.sourceBuffer),this.subscription.add(e.fromEvent(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(e=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:e})))),this.subscription.add(e.fromEvent(this.sourceBuffer,'error').subscribe((e=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:e})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((e=>this.pruneBuffer(e)))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((e=>this.error$.next(e))));const i=yield this.fetcher.fetchRepresentation(s,this.containerParser).catch((e=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:e})));if(!i)return;const{dataView:a,segments:r}=i;let o=0;for(const e of r)e.time.from-o>=300&&this.gaps.push({representation:s.id,from:o,to:e.time.from}),o=e.time.to;e.isNonNullable(s.duration)&&s.duration-o>=300&&this.gaps.push({representation:s.id,from:o,to:s.duration});const n=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(t,n),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.segments.set(t,r)}.bind(this));switchTo=e.abortable(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=t,!this.initData.has(t))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const s=this.representations.get(t);e.assertNonNullable(s);const i=yield this.fetcher.fetchRepresentation(s,this.containerParser,0).catch((e=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:e})));if(!i)return;const{dataView:a,segments:r}=i,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(t,o),this.segments.set(t,r)}const s=this.initData.get(t);e.assertNonNullable(s,`No init buffer for ${t}`),e.assertNonNullable(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),e.isNonNullable(this.playingRepresentationId)&&this.segments.get(this.playingRepresentationId)?.forEach((e=>{e.status===Oe.FED?e.status=Oe.NONE:e.status===Oe.PARTIALLY_FED&&this.abortSegment(e)}));const i=this.getCurrentPosition();e.isNonNullable(i)&&this.maintain(i)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new I,this.abortBuffer()}maintain(t){if(e.isNullable(this.downloadingRepresentationId)||e.isNullable(this.playingRepresentationId)||e.isNullable(this.sourceBuffer)||this.onLastSegment$.getValue())return;const s=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);e.assertNonNullable(s),e.assertNonNullable(i);const a=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=xe(this.sourceBuffer.buffered,t);r=t+Math.min(e,this.tuning.representationSwitchForwardBufferGap)}let o=[];isFinite(this.bufferLimit)&&(e=>{let t=0;for(let s=0;s<e.length;s++)t+=e.end(s)-e.start(s);return 1e3*t})(this.sourceBuffer.buffered)>=.8*this.bufferLimit?this.pruneBuffer(1/0):(o=this.selectForwardBufferSegments(i,r),o.length&&this.loadSegments(o,s)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&a&&a.status===Oe.FED&&!o.length&&xe(this.sourceBuffer.buffered,t)>3e3&&this.loadAllInits().catch((e=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:e})));const n=i.at(-1);n&&n.status===Oe.FED&&(this.fullyBuffered$.next(!0),a===n&&this.onLastSegment$.next(!0))}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const s=this.segments.get(t);if(!s)return;return s.find((t=>t.time.from<=e&&t.time.to>=e))?.time.from??void 0}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t){const s=e.findIndex((({status:e,time:{from:s,to:i}})=>e===Oe.NONE&&(s>t||s<=t&&i>=t)&&i<=t+this.tuning.forwardBufferTarget));if(-1===s)return[];let i=0;const a=[];for(let t=s;t<e.length&&i<=this.tuning.segmentRequestSize;t++){const s=e[t];if(i+=s.byte.to+1-s.byte.from,s.status!==Oe.NONE)break;a.push(s)}return a}async loadSegments(t,s){if(!t.length)return;const i=t.at(0).byte.from,a=t.at(-1).byte.to;for(const e of t)e.status=Oe.DOWNLOADING,this.activeSegments.add({segment:e,loadedBytes:0,fedBytes:0});const{signal:r}=this.downloadAbortController;return this.segmentDownloadPromise=this.segmentDownloadPromise.then(e.abortable(this.destroyAbortController.signal,async function*(){if(r.aborted)for(const e of t)this.abortSegment(e);else yield this.fetcher.fetchRange(s.url,i,a,{method:Fe.PARAM,onProgress:(e,t)=>this.onSomeDataLoaded(e,s.id,i,t,r),signal:r})}.bind(this))).catch((e=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:e}))),this.segmentDownloadPromise}onSomeDataLoaded(e,t,s,i,a){if(!this.activeSegments.size)return;const r=e=>{this.abortSegment(e.segment)},o=e=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),e.segment.status=Oe.FED,this.activeSegments.delete(e),this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback((()=>{try{this.detectGaps(t,[e.segment])}catch(e){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:e})}this.gapDetectionIdleCallback=null})))};for(const t of this.activeSegments){const{segment:n}=t,d=n.byte.to-n.byte.from+1;if(a.aborted)return void r(t);const u=n.byte.from>=s,h=n.byte.from<s+i,c=n.byte.to<=s+i;if(n.status===Oe.DOWNLOADING&&u&&h&&c){n.status=Oe.DOWNLOADED,this.activeSegments.delete(t);const u=new DataView(e.buffer,e.byteOffset+n.byte.from-s,Math.min(d,s+i-n.byte.from));this.sourceBufferTaskQueue.append(u,a).then((e=>e&&!a.aborted?o(t):r(t)))}else if(this.tuning.enableSubSegmentBufferFeeding&&u&&h){const u=Math.min(d,i-(n.byte.from-s));t.buffer=t.buffer??new ArrayBuffer(d);const h=new DataView(t.buffer);for(let i=t.loadedBytes;i<u;i++)h.setUint8(i,e.getUint8(n.byte.from-s+i));t.loadedBytes=u;const c=new DataView(t.buffer,t.fedBytes,t.loadedBytes-t.fedBytes);if(d===t.loadedBytes&&t.fedBytes!==t.loadedBytes)n.status=Oe.DOWNLOADED,t.fedBytes=t.loadedBytes,this.sourceBufferTaskQueue.append(c,a).then((e=>e&&!a.aborted?o(t):r(t)));else if(t.loadedBytes>t.fedBytes){const e=this.containerParser.parseFeedableSegmentChunk(c);e&&(n.status=Oe.PARTIALLY_FED,t.fedBytes+=e.byteLength,this.sourceBufferTaskQueue.append(e,a).then((e=>{e&&!a.aborted||r(t)})))}}}}abortSegment(e){e.status===Oe.DOWNLOADING?e.status=Oe.NONE:e.status===Oe.PARTIALLY_FED&&this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then((()=>e.status=Oe.NONE));for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}async loadAllInits(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=Promise.all(Array.from(this.representations.entries()).map((([e,t])=>this.initData.has(e)?Promise.resolve():this.fetcher.fetchRepresentation(t,this.containerParser).then((t=>{if(!t)return;const{dataView:s,segments:i}=t,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(e,a),this.segments.set(e,i)}))))).then((()=>{this.allInitsLoaded=!0})).finally((()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}async pruneBuffer(t){const s=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||e.isNullable(s))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let a=0,r=1/0,o=-1/0,n=!1;for(const e of i){if(e.time.to>=s||a>=t)break;e.status===Oe.FED&&(r=Math.min(r,e.time.from),o=Math.max(o,e.time.to),a+=e.byte.to-e.byte.from)}if(n=isFinite(r)&&isFinite(o)&&(a>=t||t===1/0),!n){a=0,r=1/0,o=-1/0;for(const e of i)e.status===Oe.FED&&e.time.from>s+this.tuning.forwardBufferTarget&&(r=Math.min(r,e.time.from),o=Math.max(o,e.time.to),a+=e.byte.to-e.byte.from)}return n=isFinite(r)&&isFinite(o)&&(a>=t||t===1/0),!!n&&(await this.sourceBufferTaskQueue.remove(r,o/1e3),!0)}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(e){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:e})}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let t={representation:e,from:s.time.from,to:s.time.to};for(let e=0;e<this.sourceBuffer.buffered.length;e++){const i=1e3*this.sourceBuffer.buffered.start(e),a=1e3*this.sourceBuffer.buffered.end(e);if(!(a<=s.time.from||i>=s.time.to)){if(i<=s.time.from&&a>=s.time.to){t=void 0;break}a>s.time.from&&a<s.time.to&&(t.from=a),i<s.time.to&&i>s.time.from&&(t.to=i)}}t&&t.to-t.from>=1&&this.gaps.push(t)}}checkEjectedSegments(){if(e.isNullable(this.sourceBuffer)||e.isNullable(this.playingRepresentationId))return;const t=this.segments.get(this.playingRepresentationId);if(e.isNullable(t))return;const s=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const t=1e3*this.sourceBuffer.buffered.start(e),i=1e3*this.sourceBuffer.buffered.end(e);s.push({from:t,to:i})}const i=this.tuning.segmentTimelineTolerance;for(const e of t){const t=s.some((t=>t.from-i<=e.time.from&&t.to+i>=e.time.to));e.status!==Oe.FED||t||(e.status=Oe.NONE)}}}const it=e=>{if(!e.startsWith('P'))return;const t=(e,t)=>{const s=e?parseFloat(e.replace(',','.')):NaN;return(isNaN(s)?0:s)*t},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(e),i='-'===s?.[1]?-1:1;return 24*t(s?.[5],i)*60*600*1e3+60*t(s?.[6],i)*600*1e3+60*t(s?.[7],i)*1e3+1e3*t(s?.[8],i)},at=['timeupdate','progress','play','seeked','stalled'];var rt,ot;!function(e){e.NONE='none',e.MANIFEST_LOADED='manifest_loaded',e.REPRESENTATION_SELECTED='representation_selected'}(rt||(rt={}));class nt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new e.Subscription;fetcher;state$=new k(rt.NONE);currentVideoRepresentation$=new e.ValueSubject(void 0);error$=new e.Subject;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);forceEnded$=new e.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new I;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ue({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=e.abortable(this.destroyController.signal,async function*(t,s){this.element=t,this.state$.startTransitionTo(rt.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(s);if(!i)return null;let a;try{a=((t,s)=>{const i={video:[],audio:[],text:[]},a=(new DOMParser).parseFromString(t,'application/xml').children[0],r=a.getElementsByTagName('Period')[0],o=r.children;let n;const d=a.getAttribute('mediaPresentationDuration'),u=r.getAttribute('duration');if(d)n=it(d);else if(u){const t=it(u);e.isNonNullable(t)&&(n=t)}let h=0;const c=a.getAttribute('profiles')?.split(',')??[],l=c.includes(Be.WEBM_AS_IN_FFMPEG)||c.includes(Be.WEBM_AS_IN_SPEC)?Ve.WEBM:Ve.MP4;for(const e of o){const t=e.getAttribute('mimeType'),a=e.getAttribute('codecs'),r=e.getAttribute('contentType')??t?.split('/')[0],o=e.getAttribute('profiles')?.split(',')??[],d=e.querySelectorAll('Representation');for(const u of d){const d=u.getAttribute('mimeType')??t,l=u.getAttribute('codecs')??a??'',p=u.getAttribute('contentType')??d?.split('/')[0]??r,m=e.getAttribute('profiles')?.split(',')??[],S=parseInt(u.getAttribute('width')??'',10),f=parseInt(u.getAttribute('height')??'',10),b=parseInt(u.getAttribute('bandwidth')??'',10)/1e3,g=u.getAttribute('frameRate')??'',v=u.getAttribute('quality')??void 0,y=g?ee(g):void 0,T=`${u.getAttribute('id')??(h++).toString(10)}@${'video'===p?`${f}p`:'audio'===p?`${b}Kbps`:l}`,E=u.querySelector('BaseURL')?.textContent?.trim()??'',k=new URL(E,s).toString(),$=[...c,...o,...m],P=u.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[w,A]=P.split('-').map((e=>parseInt(e,10))),x={from:w,to:A},N=u.querySelector('SegmentBase')?.getAttribute('indexRange'),[_,D]=N?N.split('-').map((e=>parseInt(e,10))):[],R=N?{from:_,to:D}:void 0;if(!p||!d)continue;const I={video:Le.VIDEO,audio:Le.AUDIO,text:Le.TEXT}[p];I&&i[I].push({id:T,kind:I,duration:n,profiles:$,initRange:x,indexRange:R,bitrate:b,mime:d,codecs:l,width:S,height:f,fps:y,quality:v,url:k})}}return{container:l,representations:i}})(i??'',s)}catch(e){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:e})}e.assertNonNullable(a);const r=({mime:e,codecs:s})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${s}"`));return this.manifest={...a,representations:Object.fromEntries(Object.entries(a.representations).map((([e,t])=>[e,t.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(rt.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this));initRepresentations=e.abortable(this.destroyController.signal,async function*(t,s){e.assertNonNullable(this.manifest),e.assertNonNullable(this.element),this.state$.startTransitionTo(rt.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning.dash,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new st(Le.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new st(Le.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),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$)),this.subscription.add(e.merge(this.forceEnded$,e.merge(this.videoBufferManager.onLastSegment$,this.audioBufferManager.onLastSegment$,this.videoBufferManager.fullyBuffered$,this.audioBufferManager.fullyBuffered$).pipe(e.filter((()=>!(!this.videoBufferManager||!this.audioBufferManager)&&[this.videoBufferManager.fullyBuffered$.getValue(),this.audioBufferManager.fullyBuffered$.getValue()].every((e=>e))&&[this.videoBufferManager.onLastSegment$.getValue(),this.audioBufferManager.onLastSegment$.getValue()].some((e=>e)))))).subscribe((()=>{if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((e=>!e.updating)))try{this.source?.endOfStream()}catch(e){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:e})}}))),this.subscription.add(e.merge(this.videoBufferManager.error$,this.audioBufferManager.error$).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((e=>this.source?.addEventListener('sourceopen',e)))),yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]),this.state$.setState(rt.REPRESENTATION_SELECTED),e.assertNonNullable(this.element),this.subscription.add(e.merge(...at.map((t=>e.fromEvent(this.element,t))),e.fromEvent(window,'online')).subscribe(this.tick,(e=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:e})}))),this.subscription.add(e.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(e.fromEvent(this.element,'waiting').subscribe((()=>{if(this.element&&2===this.element.readyState&&!this.element.seeking)for(let e=0;e<this.element.buffered.length;e++){if(this.element.buffered.start(e)<=this.element.currentTime&&this.element.buffered.end(e)>this.element.currentTime){this.element.currentTime=this.element.currentTime;break}}}))),this.tick()}.bind(this));async switchRepresentation(t,s){const i={[Le.VIDEO]:this.videoBufferManager,[Le.AUDIO]:this.audioBufferManager,[Le.TEXT]:null}[t];return e.assertNonNullable(i),i.switchTo(s)}seek(t,s){let i;e.assertNonNullable(this.element),e.assertNonNullable(this.videoBufferManager),e.assertNonNullable(this.audioBufferManager),this.videoBufferManager.abort(),this.audioBufferManager.abort(),i=s||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(this.videoBufferManager.findSegmentStartTime(t)??t,this.audioBufferManager.findSegmentStartTime(t)??t),this.videoBufferManager.maintain(i),this.audioBufferManager.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.state$.setState(rt.NONE)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=e.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(e=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:e})})),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const e=1e3*this.element.currentTime,t=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const s of[this.videoBufferManager,this.audioBufferManager])for(const i of s.gaps)if(s.playingRepresentation$.getValue()===i.representation&&i.from-t<=e&&i.to+t>e){if(1e3*this.element.duration-i.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=i.to/1e3;break}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ot||(ot={}));const dt=({id:e,width:t,height:s,bitrate:i,fps:a,quality:r})=>{const o=(r?me(r):void 0)??T({width:t,height:s});return o&&{id:e,quality:o,bitrate:i,size:{width:t,height:s},fps:a}},ut=(e,t,s)=>{const i=Array.from(t).sort(((e,t)=>t.bitrate-e.bitrate)).indexOf(s);return e.at(Math.round(e.length*i/t.length))??e.at(-1)};class ht{subscription=new e.Subscription;videoState=new k(ot.STOPPED);video;player;params;elementSize$=new e.ValueSubject(void 0);textTracksManager=new Y;videoTracks=[];audioRepresentations;constructor(e){this.params=e,this.video=Q(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new nt({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=Z(this.video),a=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},r=(e,t)=>this.subscription.add(e.subscribe(t,a));r(i.timeUpdate$,t.position$),r(i.durationChange$,t.duration$),r(i.ended$,t.endedEvent$),r(i.looped$,t.loopedEvent$),r(i.error$,t.error$),r(i.isBuffering$,t.isBuffering$),r(i.currentBuffer$,t.currentBuffer$),r(i.firstFrame$,t.firstFrameEvent$),r(this.player.error$,t.error$),r(this.player.lastConnectionType$,t.httpConnectionType$),r(this.player.lastConnectionReused$,t.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(e.filter(e.isNonNullable),e.once()),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(H(this.video,s.isLooped,a)),this.subscription.add(j(this.video,s.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),r(ue(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(ot.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(ot.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===ot.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(e.filter((({to:e})=>e===rt.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(ot.READY)}))),this.subscription.add(e.merge(this.player.state$.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,s.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,e.fromEvent(this.video,'progress')).subscribe((()=>{const t=this.player.state$.getState(),i=this.player.state$.getTransition();if(t===rt.NONE||!this.videoTracks.length)return;const a=t===rt.MANIFEST_LOADED&&!i,r=s.autoVideoTrackSwitching.getState(),o=s.videoTrack.getState(),n=this.videoTracks.find((({track:{id:e}})=>e===o))?.track;s.autoVideoTrackSwitching.getTransition()&&s.autoVideoTrackSwitching.setState(r);const d=xe(this.video.buffered,1e3*this.video.currentTime),u=Math.min(d/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),h=ne(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:s.autoVideoTrackLimits.getState(),forwardBufferHealth:u}),c=r?h??n:n??h;if(a){const t=c&&this.videoTracks.find((({track:e})=>e===c))?.representation;e.assertNonNullable(t);const s=ut(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),t);e.assertNonNullable(s),this.player.initRepresentations(t.id,s.id)}else{const e=c&&this.videoTracks.find((({track:e})=>e===c))?.representation;if(e){const t=ut(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),e);this.player.switchRepresentation(Le.VIDEO,e.id),t&&this.player.switchRepresentation(Le.AUDIO,t.id)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(e.filterChanged(),e.map((e=>e&&this.videoTracks.find((({representation:{id:t}})=>t===e))?.track))).subscribe(t.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,s,t);const o=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,a))}async prepare(){const t=await this.player.initManifest(this.video,this.params.source.url);e.assertNonNullable(t),this.videoTracks=[];for(const e of t.representations.video){const t=dt(e);t&&this.videoTracks.push({track:t,representation:e})}this.audioRepresentations=Array.from(t.representations.audio).sort(((e,t)=>t.bitrate-e.bitrate)),this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:e})=>e)))}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(a.state===h.Requested&&i?.to!==exports.PlaybackState.PAUSED&&t!==ot.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),s!==exports.PlaybackState.STOPPED){if(t===ot.STOPPED)return this.videoState.startTransitionTo(ot.READY),void this.prepare();switch(t){case ot.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(ot.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ot.PLAYING),this.playIfAllowed()));case ot.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ot.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case ot.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ot.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==ot.STOPPED&&(this.videoState.startTransitionTo(ot.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(ot.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(ot.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const ct={};var lt;!function(e){e.INITIALIZING='initializing',e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(lt||(lt={}));const pt=(t,s)=>new e.Observable((e=>{const i=(t,s)=>e.next(s);return t.on(s,i),()=>t.off(s,i)}));class mt{subscription=new e.Subscription;videoState=new k(lt.INITIALIZING);video;params;hls;textTracksManager=new Y;trackLevels=new Map;constructor(e){this.video=Q(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=t=>{e||this.params.output.error$.next({id:'timeout'===t?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:t}),e=!0},i=window.setTimeout((()=>t('timeout')),5e3);Promise.resolve().then((function(){return s(require('hls.js'))})).then((t=>{e||(ct.Hls=t.default,ct.Events=t.default.Events,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(ct.Hls,'hls.js not loaded'),this.hls=new ct.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(lt.STOPPED)}subscribe(){e.assertNonNullable(ct.Events,'hls.js not loaded');const{desiredState:t,output:s}=this.params,i=e=>{s.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,s.position$),r(a.durationChange$,s.duration$),r(a.ended$,s.endedEvent$),r(a.looped$,s.loopedEvent$),r(a.error$,s.error$),r(a.isBuffering$,s.isBuffering$),r(a.currentBuffer$,s.currentBuffer$),r(a.firstBytes$,s.firstBytesEvent$),r(a.firstFrame$,s.firstFrameEvent$),r(a.seeked$,s.seekedEvent$),this.subscription.add(H(this.video,t.isLooped,i)),this.subscription.add(j(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.hls,ct.Events.ERROR).subscribe((e=>{e.fatal&&s.error$.next({id:['HlsJsFatal',e.type,e.details].join('_'),message:`HlsJs fatal ${e.type} ${e.details}, ${e.err?.message} ${e.reason}`,thrown:e.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(lt.PLAYING),f(t.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(lt.PAUSED),f(t.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===lt.READY&&this.videoState.setState(lt.READY),this.videoState.getState()===lt.PLAYING&&this.playIfAllowed()}),i)),r(pt(this.hls,ct.Events.MANIFEST_PARSED).pipe(e.map((({levels:e})=>e.reduce(((e,t)=>{const s=t.name||t.height.toString(10),{width:i,height:a}=t,r=me(t.attrs.QUALITY??'')??T({width:i,height:a});if(!r)return e;const o=t.attrs['FRAME-RATE']?parseFloat(t.attrs['FRAME-RATE']):void 0,n={id:s.toString(),quality:r,bitrate:t.bitrate/1e3,size:{width:i,height:a},fps:o};return this.trackLevels.set(s,{track:n,level:t}),e.push(n),e}),[])))),s.availableVideoTracks$),r(pt(this.hls,ct.Events.LEVEL_LOADING).pipe(e.map((({url:e})=>de(e)))),s.hostname$),this.subscription.add(q(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(e=>{this.hls.nextLevel=e?-1:this.hls.currentLevel,this.hls.loadLevel=e?-1:this.hls.loadLevel}),{onError:i}));const o=e=>Array.from(this.trackLevels.values()).find((({level:t})=>t===e))?.track,n=pt(this.hls,ct.Events.LEVEL_SWITCHED).pipe(e.map((({level:e})=>o(this.hls.levels[e]))));n.pipe(e.filter(e.isNonNullable)).subscribe(s.currentVideoTrack$,i),this.subscription.add(q(t.videoTrack,(()=>o(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(e.isNullable(t))return;const s=this.trackLevels.get(t)?.level;if(!s)return;const i=this.hls.levels.indexOf(s),a=this.hls.currentLevel,r=this.hls.levels[a];!r||s.bitrate>r.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:n.pipe(e.map((e=>e?.id))),onError:i})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,s);const d=e.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==lt.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===h.Requested&&this.seek(a.position),s){case exports.PlaybackState.STOPPED:switch(t){case lt.STOPPED:break;case lt.READY:case lt.PLAYING:case lt.PAUSED:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case lt.PLAYING:break;case lt.STOPPED:this.prepare();break;case lt.READY:case lt.PAUSED:this.playIfAllowed();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case lt.PAUSED:break;case lt.STOPPED:this.prepare();break;case lt.READY:this.videoState.setState(lt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case lt.PLAYING:this.pause();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};prepare(){this.videoState.startTransitionTo(lt.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(lt.PLAYING);await Se(this.video)||(this.videoState.setState(lt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(lt.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(lt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const St=e=>{let t=null;if(e.QUALITY&&(t=me(e.QUALITY)),!t&&e.RESOLUTION){const[s,i]=e.RESOLUTION.split('x').map((e=>parseInt(e,10)));t=T({width:s,height:i})}return t??null},ft=async(e,t=e)=>{const s=await R(e),i=(await s.text()).split('\n'),a=[];for(let e=0;e<i.length;e++){const s=i[e].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const r=Object.fromEntries(s[1].split(',').map((e=>e.split('=')))),o=r.QUALITY??`stream-${r.BANDWIDTH}`,n=St(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const u=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let h;if(r.RESOLUTION){const[e,t]=r.RESOLUTION.split('x').map((e=>parseInt(e,10)));e&&t&&(h={width:e,height:t})}const c=new URL(i[++e],t).toString();n&&a.push({id:o,quality:n,url:c,bandwidth:d,size:h,fps:u})}return a};var bt,gt,vt;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(bt||(bt={}));class yt{subscription=new e.Subscription;videoState=new k(bt.STOPPED);video;params;textTracksManager=new Y;manifests$=new e.ValueSubject([]);maxSeekBackTime$;liveOffset=new z;manifestStartTime$=new e.ValueSubject(void 0);constructor(t){this.params=t,this.video=Q(t.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]),ft(S(this.params.source.url),this.params.source.url).then((e=>{this.manifests$.next([s,...e])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:e}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.maxSeekBackTime$=new e.ValueSubject(t.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??'master',r=this.manifests$.getValue();if(!r)return;const o=s?'master':a;return s&&!i&&t.startTransitionTo('master'),r.find((e=>e.id===o))}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),this.subscription.add(s.isLooped.stateChangeStarted$.subscribe((()=>s.isLooped.setState(!1)),i)),this.subscription.add(j(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(bt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(bt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===bt.READY&&this.videoState.setState(bt.READY),this.videoState.getState()===bt.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map((e=>-e/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&e.isNonNullable(i.to)){const e=i.to;this.params.desiredState.videoTrack.setState(e);const t=this.manifests$.getValue().find((t=>t.id===e));t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(de(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===bt.CHANGING_MANIFEST&&this.videoState.setState(s.to),t&&t.state===h.Requested&&this.seek(t.position)}),i)),this.subscription.add(a.loadedData$.subscribe((()=>{const e=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(e||void 0)}),i)),this.subscription.add(e.combine({startTime:this.manifestStartTime$.pipe(e.filter(e.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:e,currentTime:t})=>this.params.output.liveTime$.next(e+1e3*t)),i)),this.subscription.add(this.manifests$.pipe(e.map((e=>e.map((({id:e,quality:t,size:s,bandwidth:i,fps:a})=>({id:e,quality:t,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.stateChangeStarted$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(e.isNullable(t))return;const s=S(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',s),this.video.load(),(async e=>{const t=await R(e,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0})(s).then((t=>{e.isNullable(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(bt.PAUSED),this.liveOffset.pause(),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==bt.STOPPED&&(this.videoState.startTransitionTo(bt.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(bt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===bt.STOPPED)return this.videoState.startTransitionTo(bt.READY),void this.prepare();if(a||r){const e=this.videoState.getState();return this.videoState.setState(bt.CHANGING_MANIFEST),this.videoState.startTransitionTo(e),this.prepare(),void(o.state===h.None&&this.params.desiredState.seekState.setState({state:h.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if(i?.to!==exports.PlaybackState.PAUSED&&o.state===h.Requested)return this.videoState.startTransitionTo(bt.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case bt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(bt.PAUSED),this.liveOffset.pause(),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(bt.PLAYING),this.playIfAllowed()));case bt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(bt.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case bt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(bt.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):i?.to===exports.PlaybackState.PAUSED&&(f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case bt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(gt||(gt={}));class Tt{subscription=new e.Subscription;videoState=new k(gt.STOPPED);video;params;textTracksManager=new Y;manifests$=new e.ValueSubject([]);constructor(e){this.params=e,this.video=Q(e.container),this.params.output.element$.next(this.video);const t={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),ft(this.params.source.url).then((e=>{this.manifests$.next([t,...e])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:e}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??'master',r=this.manifests$.getValue();if(!r)return;const o=s?'master':a;return s&&!i&&t.startTransitionTo('master'),r.find((e=>e.id===o))}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(H(this.video,s.isLooped,i)),this.subscription.add(j(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(gt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(gt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===gt.READY&&this.videoState.setState(gt.READY),this.videoState.getState()===gt.PLAYING&&this.playIfAllowed()}),i).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&e.isNonNullable(i.to)){const e=i.to;this.params.desiredState.videoTrack.setState(e);const t=this.manifests$.getValue().find((t=>t.id===e));t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(de(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===gt.CHANGING_MANIFEST&&this.videoState.setState(s.to),t.state===h.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(e.map((e=>e.map((({id:e,quality:t,size:s,bandwidth:i,fps:a})=>({id:e,quality:t,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();e.isNullable(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(gt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==gt.STOPPED&&(this.videoState.startTransitionTo(gt.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(gt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===gt.STOPPED)return this.videoState.startTransitionTo(gt.READY),void this.prepare();if(a||r){const e=this.videoState.getState();this.videoState.setState(gt.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const{currentTime:t}=this.video;return this.prepare(),void(o.state===h.None&&this.params.desiredState.seekState.setState({state:h.Requested,position:1e3*t,forcePrecise:!0}))}switch(i?.to!==exports.PlaybackState.PAUSED&&o.state===h.Requested&&this.seek(o.position),t){case gt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(gt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(gt.PLAYING),this.playIfAllowed()));case gt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(gt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case gt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(gt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case gt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(vt||(vt={}));class Et{subscription=new e.Subscription;videoState=new k(vt.STOPPED);video;trackUrls={};params;textTracksManager=new Y;constructor(e){this.params=e,this.video=Q(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([e,t],s)=>{const i=s.toString(10);this.trackUrls[i]={track:{quality:e,id:i},url:t}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:e})=>e))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(H(this.video,s.isLooped,i)),this.subscription.add(j(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(vt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(vt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===vt.READY&&this.videoState.setState(vt.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&e.isNonNullable(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===vt.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(s.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>s.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,s,t);const o=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();e.assertNonNullable(t,'MpegProvider: track is not selected');let{url:s}=this.trackUrls[t];e.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=F(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(de(s))}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(vt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==vt.STOPPED&&(this.videoState.startTransitionTo(vt.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(vt.STOPPED),f(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(t===vt.STOPPED)return this.videoState.startTransitionTo(vt.READY),void this.prepare();if(a){const{currentTime:e}=this.video;return this.prepare(),void(r.state===h.None&&this.params.desiredState.seekState.setState({state:h.Requested,position:1e3*e,forcePrecise:!0}))}switch(i?.to!==exports.PlaybackState.PAUSED&&r.state===h.Requested&&this.seek(r.position),t){case vt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(vt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(vt.PLAYING),this.playIfAllowed()));case vt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(vt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case vt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(vt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}class kt{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const $t=(()=>{const{userAgent:e}=window.navigator;return!/chrome/i.test(e)&&/webkit|safari|khtml/i.test(e)})(),Pt=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),wt=document.createElement('video'),At={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(wt.canPlayType?.('application/x-mpegurl')||wt.canPlayType?.('vnd.apple.mpegURL'))},xt={mp4:Boolean(wt.canPlayType?.('video/mp4')),webm:Boolean(wt.canPlayType?.('video/webm'))},Nt={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},_t=(Nt.h264||Nt.h265)&&Nt.aac,Dt=!$t,Rt=Pt||$t,It=!At.hls||!Rt;const Ct=3e4,Lt=18e4,Bt=3,Ot=100,Vt={cacheDuration:12e4},Mt={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},Ft={maxPausedTime:3e4},Ut={maxPausedTime:3e4};class qt{current$=new e.ValueSubject({type:void 0});providerError$=new e.Subject;noAvailableProvidersError$=new e.Subject;providerOutput={position$:new e.ValueSubject(0),duration$:new e.ValueSubject(1/0),volume$:new e.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new e.ValueSubject(void 0),availableVideoTracks$:new e.ValueSubject([]),autoVideoTrackLimitingAvailable$:new e.ValueSubject(!1),currentBuffer$:new e.ValueSubject(void 0),isBuffering$:new e.ValueSubject(!0),error$:new e.Subject,willSeekEvent$:new e.Subject,seekedEvent$:new e.Subject,loopedEvent$:new e.Subject,endedEvent$:new e.Subject,firstBytesEvent$:new e.Subject,firstFrameEvent$:new e.Subject,isLive$:new e.ValueSubject(void 0),liveTime$:new e.ValueSubject(void 0),availableTextTracks$:new e.ValueSubject([]),currentTextTrack$:new e.ValueSubject(void 0),hostname$:new e.ValueSubject(void 0),httpConnectionType$:new e.ValueSubject(void 0),httpConnectionReused$:new e.ValueSubject(void 0),element$:new e.ValueSubject(void 0)};subscription=new e.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:s}=this.params.tuning,i=s.length?[...t.screenFormatsPriority.filter((e=>!s.includes(e))),...t.screenFormatsPriority.filter((e=>s.includes(e)))]:t.screenFormatsPriority;this.screenFormatsIterator=new kt(i.filter((s=>e.isNonNullable(t.sources[s]))).filter((t=>{switch(t){case exports.VideoFormat.DASH:return At.mse&&xt.mp4&&_t&&Dt;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return At.mse&&xt.mp4&&_t;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return At.mse&&xt.webm&&Nt.vp9&&Nt.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return At.mse&&xt.mp4&&_t;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return At.hls&&xt.mp4&&Rt;case exports.VideoFormat.HLS_JS:return At.mse&&xt.mp4&&_t&&It;case exports.VideoFormat.MPEG:return xt.mp4;default:return e.assertNever(t)}}))),this.chromecastFormatsIterator=new kt(t.chromecastFormatsPriority.filter((s=>e.isNonNullable(t.sources[s]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),s=this.chooseFormat(t);if(e.isNullable(s))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,s)}catch(e){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:e})}i?this.current$.next({type:s,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;e.assertNonNullable(t),this.skipFormat(t),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:'destroyProvider'});const t=this.params.desiredState.seekState.getState();t.state!==h.Requested&&t.state!==h.Applying||this.params.desiredState.seekState.setState({...t,state:h.Requested}),e.destroy();const s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(t,s){switch(this.log({message:`createProvider: ${t}:${s}`}),t){case o.SCREEN:return this.createScreenProvider(s);case o.CHROMECAST:return this.createChromecastProvider(s);default:return e.assertNever(t)}}createScreenProvider(t){const{sources:s,container:i,desiredState:a}=this.params,r=this.providerOutput;switch(t){case exports.VideoFormat.DASH:{const o=s[t];return e.assertNonNullable(o),new Ce({container:i,source:o,desiredState:a,output:r,config:Vt,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const o=s[t];return e.assertNonNullable(o),new ht({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const o=s[t];return e.assertNonNullable(o),new pe({container:i,source:o,desiredState:a,output:r,format:t,config:Ut,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=s[t];return e.assertNonNullable(o),new Tt({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const o=s[t];return e.assertNonNullable(o),new yt({container:i,source:o,desiredState:a,output:r,config:Ft,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const o=s[t];return e.assertNonNullable(o),new mt({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const o=s[t];return e.assertNonNullable(o),new Et({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const o=s[t];return e.assertNonNullable(o),new we({container:i,source:o,desiredState:a,output:r,config:Mt,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return e.assertNever(t)}}createChromecastProvider(t){const{sources:s,container:i,desiredState:a,meta:r}=this.params,o=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return e.assertNonNullable(n),new P({connection:n,meta:r,container:i,source:s,format:t,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(t){switch(t){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 e.assertNever(t)}}skipFormat(t){switch(t){case o.SCREEN:return this.screenFormatsIterator.next();case o.CHROMECAST:return this.chromecastFormatsIterator.next();default:return e.assertNever(t)}}handleNoFormatsError(t){switch(t){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 e.assertNever(t)}}initProviderErrorHandling(){let t=[],s=0;const i=new e.Subscription;var a;return i.add(e.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ct,position$:this.providerOutput.position$,providerChanged$:this.current$},new e.Observable((t=>{const s=new e.Subscription,i=e.timeout(a.maxTransitionInterval),r=new e.ValueSubject(void 0);e.merge(a.desiredPlaybackState$.stateChangeStarted$.pipe(e.mapTo(i)),a.desiredPlaybackState$.stateChangeEnded$.pipe(e.mapTo(void 0)),a.providerChanged$.pipe(e.map((()=>r.getValue())))).subscribe(r);const o=new e.Subscription;return s.add(o),s.add(r.subscribe((e=>{o.unsubscribe(),e&&o.add(e.subscribe(t))}))),s}))).pipe(e.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),i.add(this.providerError$.pipe(e.throttle(Ot,{leading:!1,trailing:!0})).subscribe((()=>{const i=Date.now();this.current$.getValue().destination===o.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):e.isNonNullable(t[s])&&i<t[s]+Lt?(t=[],this.switchToNextProvider()):(t[s]=i,this.reinitProvider()),s=(s+1)%Bt}))),i}}const Ht=(e,t,s)=>s*t+(1-s)*e;class jt{prevReported=void 0;slow;fast;smoothed;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(t){this.params=t,this.slow=this.fast=this.smoothed=this.prevReported=t.initial,this.smoothed$=new e.ValueSubject(t.initial),this.debounced$=new e.ValueSubject(t.initial);const s=t.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${s}`),this.smoothedSeries$=new re(`smoothed_${s}`),this.reportedSeries$=new re(`reported_${s}`)}next(t){this.slow=Ht(this.slow,t,this.params.emaAlphaSlow),this.fast=Ht(this.fast,t,this.params.emaAlphaFast);const s=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=s(this.slow,this.fast),this.smoothed$.next(this.smoothed),(e.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)),this.rawSeries$.next(t),this.smoothedSeries$.next(this.smoothed)}}var Gt;!function(e){e[e.LOCAL_STORAGE=0]='LOCAL_STORAGE',e[e.SESSION_STORAGE=1]='SESSION_STORAGE',e[e.RUNTIME=2]='RUNTIME'}(Gt||(Gt={}));const Yt=new Map;let Qt=Gt.RUNTIME;const zt=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(zt,'test'),localStorage.removeItem(zt),Qt=Gt.LOCAL_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;try{sessionStorage.getItem(zt),Qt=Gt.SESSION_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;Qt=Gt.RUNTIME}}})();const Wt=(t,s)=>{switch(Qt){case Gt.LOCAL_STORAGE:try{localStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Gt.SESSION_STORAGE:try{sessionStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Gt.RUNTIME:return void Yt.set(t,s);default:e.assertNever(Qt)}},Jt=window.navigator.connection,Kt=()=>{const t=Jt?.downlink;if(e.isNonNullable(t)&&10!==t)return 1e3*t},Xt=()=>{const t=Jt?.rtt;if(e.isNonNullable(t)&&3e3!==t)return t},Zt=(e,t,s)=>{const i=8*s;return i/(i/e+t)};class es{throughput;rtt;subscription=new e.Subscription;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(t){this.tuningConfig=t;const s=es.load('one_video_throughput')||(t.useBrowserEstimation?Kt():void 0)||5e3,i=es.load('one_video_rtt')??(t.useBrowserEstimation?Xt():void 0)??0;if(this.throughput$=new e.ValueSubject(s),this.rtt$=new e.ValueSubject(i),this.rttAdjustedThroughput$=new e.ValueSubject(Zt(s,i,t.rttPenaltyRequestSize)),this.throughput=new jt({initial:s,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new jt({initial:i,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:1,label:'rtt'}),t.useBrowserEstimation){const t=()=>{const t=Kt();t&&this.throughput.next(t);const s=Xt();e.isNonNullable(s)&&this.rtt.next(s)};Jt&&'onchange'in Jt&&this.subscription.add(e.fromEvent(Jt,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((e=>{Wt('one_video_throughput',e.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((e=>{Wt('one_video_rtt',e.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(e.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(e.map((({throughput:e,rtt:s})=>Zt(e,s,t.rttPenaltyRequestSize))),e.filter((e=>{const s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(e-s)/s>=t.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(t){let s=0,i=e.now();const a=new e.Subscription;switch(this.subscription.add(a),t.readyState){case 4:break;case 3:case 2:a.add(e.fromEvent(t,'progress').pipe(e.once()).subscribe((t=>{s=t.loaded,i=e.now()})));break;case 1:case 0:a.add(e.fromEvent(t,'loadstart').subscribe((()=>{s=0,i=e.now()})))}a.add(e.fromEvent(t,'loadend').subscribe((r=>{if(200===t.status){const t=r.loaded,a=e.now(),o=t-s,n=a-i;this.addRawSpeed(o,n)}a.unsubscribe()})))}trackStream(t){const s=t.getReader();if(!s)return void t.cancel('Could not get reader');let i=0;const a=e.now();let r=0,o=e.now();const n=e=>{s.releaseLock(),t.cancel(`Throughput Estimator error: ${e}`).catch((()=>{}))},d=async({done:t,value:u})=>{t?this.addRawSpeed(i,e.now()-a):u&&(i+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&e.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,e.now()-o),r=0,o=e.now()),await(s?.read().then(d,n)))};s?.read().then(d,n)}addRawSpeed(e,t){if(es.sanityCheck(e,t)){const s=8*e/t;this.throughput.next(s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=8*e/t;return!(!s||!isFinite(s))&&(!(s>1e6)&&(!(s<30)&&(!(e<10240)&&!(t<=20))))}static load(t){const s=(t=>{switch(Qt){case Gt.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Gt.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Gt.RUNTIME:return Yt.get(t);default:e.assertNever(Qt)}})(t);if(e.isNonNullable(s))return parseInt(s,10)??void 0}}const ts={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.2,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!1},dash:{extraInitSize:1e3,forwardBufferTarget:3e4,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_SEP_VK],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1};const ss=(t=(e=>e))=>({playbackState:s,seekState:i,playbackAbort$:a,looped$:r,position$:o})=>new e.Observable((n=>{let d;const u=s.transitionEnded$.pipe(e.filter((e=>(e.from===exports.PlaybackState.PAUSED||e.from===exports.PlaybackState.STOPPED)&&e.to===exports.PlaybackState.PLAYING))),c=s.stateChangeEnded$.pipe(e.filter((e=>e.from===exports.PlaybackState.PLAYING&&e.to===exports.PlaybackState.PAUSED))),l=i.stateChangeEnded$.pipe(e.filter((({to:e})=>e.state===h.Requested&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),p=i.stateChangeEnded$.pipe(e.filter((({from:e,to:t})=>e.state===h.Applying&&t.state===h.None&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),m=e.merge(u,p).pipe(e.map((()=>t(o.getValue())))),S=e.merge(e.merge(c,l,a).pipe(e.map((()=>t(o.getValue())))),r.pipe(e.map(t)));return(new e.Subscription).add(m.subscribe((e=>{d=t(e)}))).add(S.subscribe((s=>{const i=t(s);if(e.isNullable(d)||d===i)return;const a={start:d,end:i};d=void 0,n.next(a)})))})),is=ss((e=>e)),as=ss((e=>Math.round(1e3*e)+Date.now())),rs={[o.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,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 e.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return e.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return e.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return e.ValueSubject}}),exports.Player=class{subscription=new e.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new e.Logger;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;desiredState={playbackState:new k(exports.PlaybackState.STOPPED),seekState:new k({state:h.None}),volume:new k({volume:1,muted:!1}),videoTrack:new k(void 0),autoVideoTrackSwitching:new k(!0),autoVideoTrackLimits:new k({}),isLooped:new k(!1),externalTextTracks:new k([]),currentTextTrack:new k(void 0),textTrackCuesSettings:new k({})};info={playbackState$:new e.ValueSubject(exports.PlaybackState.STOPPED),position$:new e.ValueSubject(0),duration$:new e.ValueSubject(1/0),muted$:new e.ValueSubject(!1),volume$:new e.ValueSubject(1),availableQualities$:new e.ValueSubject([]),availableQualitiesFps$:new e.ValueSubject({}),currentQuality$:new e.ValueSubject(void 0),isAutoQualityEnabled$:new e.ValueSubject(!0),autoQualityLimitingAvailable$:new e.ValueSubject(!1),autoQualityLimits$:new e.ValueSubject({}),currentBuffer$:new e.ValueSubject(void 0),isBuffering$:new e.ValueSubject(!0),isStalled$:new e.ValueSubject(!1),isEnded$:new e.ValueSubject(!1),isLooped$:new e.ValueSubject(!1),isLive$:new e.ValueSubject(void 0),liveTime$:new e.ValueSubject(void 0),currentFormat$:new e.ValueSubject(void 0),availableTextTracks$:new e.ValueSubject([]),currentTextTrack$:new e.ValueSubject(void 0),throughputEstimation$:new e.ValueSubject(void 0),rttEstimation$:new e.ValueSubject(void 0),videoBitrate$:new e.ValueSubject(void 0),hostname$:new e.ValueSubject(void 0),httpConnectionType$:new e.ValueSubject(void 0),httpConnectionReused$:new e.ValueSubject(void 0),chromecastState$:new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new e.ValueSubject(void 0),intrinsicVideoSize$:new e.ValueSubject(void 0)};events={started$:new e.Subject,startAttempt$:new e.Subject,willPause$:new e.Subject,willResume$:new e.Subject,willDestruct$:new e.Subject,watchCoverageRecord$:new e.Subject,watchCoverageLive$:new e.Subject,managedError$:new e.Subject,fatalError$:new e.Subject,ended$:new e.Subject,looped$:new e.Subject,seeked$:new e.Subject,willSeek$:new e.Subject,firstBytes$:new e.Subject,firstFrame$:new e.Subject,log$:new e.Subject};experimental={element$:new e.ValueSubject(void 0),enableDebugTelemetry$:new e.ValueSubject(!1),dumpTelemetry:ie};constructor(e={}){if(this.initLogs(),this.tuning=(e=>{const t={};for(const s of Object.keys(ts)){const i=ts[s],a=e[s];Array.isArray(i)&&Array.isArray(a)?t[s]=a:t[s]='object'==typeof i&&'object'==typeof a?{...i,...a}:a??i}return t})(e),this.chromecastInitializer=new c({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new es(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(e,t,s)=>{const i=Reflect.get(e,t,s);return'function'!=typeof i?i:(...s)=>{try{return i.apply(e,s)}catch(e){const i=s.map((e=>JSON.stringify(e,((e,t)=>{const s=typeof t;return['number','string','boolean'].includes(s)?t:null===t?null:`<${s}>`})))),a=`Player.${String(t)}`,r=`Exception calling ${a} (${i.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:e}),e}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const s='string'==typeof t.container?document.getElementById(t.container):t.container;return e.assertNonNullable(s,`Wrong container or containerId {${t.container}}`),s})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new qt({screenFormatsPriority:[...rs[o.SCREEN].live,...rs[o.SCREEN].vod],chromecastFormatsPriority:[...rs[o.CHROMECAST].live,...rs[o.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:h.Requested,position:1e3*e,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e),this}setVolume(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(t){e.assertNonNullable(this.providerContainer);const s=this.providerContainer.providerOutput.availableVideoTracks$.getValue();s.length||(this.explicitInitialQuality=t);const i=s.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map((e=>({type:'external',...e})))),this}selectTextTrack(e){return(void 0===e||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((t=>t.id===e)))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){e.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(e.isNullable(t))return this.info.position$.getValue();const s=this.desiredState.seekState.getState(),i=s.state===h.None?void 0:s.position;return e.isNonNullable(i)?i/1e3:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(e.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(e.map((e=>e.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.autoQualityLimits$));const t=new e.Subscription;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING||e.to===exports.PlaybackState.PAUSED)),e.debounce(0),e.once()).subscribe((e=>{const t=e.to===exports.PlaybackState.PLAYING,s=this.info.muted$.getValue(),i=t?s?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(i)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const e=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(e)}}))).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()}})))}initProviderContainerSubscription(t){this.subscription.add(t.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekState.getState();e.state===h.Requested?this.desiredState.seekState.setState({...e,state:h.Applying}):this.events.managedError$.next({id:`WillSeekIn${e.state}`,message:'Received unexpeceted willSeek$'})}))).add(t.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===h.Applying&&(this.desiredState.seekState.setState({state:h.None}),this.events.seeked$.next())}))).add(t.current$.pipe(e.map((e=>e.type))).subscribe(this.info.currentFormat$)).add(t.current$.pipe(e.map((e=>e.destination)),e.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(t.providerOutput.availableVideoTracks$.pipe(e.map((e=>e.map((({quality:e})=>e)).sort(((e,t)=>E(e)?1:E(t)?-1:g(t,e)?1:-1))))).subscribe(this.info.availableQualities$)).add(t.providerOutput.availableVideoTracks$.subscribe((e=>{const t={};for(const s of e)s.fps&&(t[s.quality]=s.fps);this.info.availableQualitiesFps$.next(t)}))).add(t.providerOutput.currentVideoTrack$.subscribe((e=>{this.info.currentQuality$.next(e?.quality),this.info.videoBitrate$.next(e?.bitrate);const s=t.providerOutput.element$.getValue();s&&this.info.intrinsicVideoSize$.next({width:s.videoWidth,height:s.videoHeight})}))).add(t.providerOutput.hostname$.pipe(e.filterChanged()).subscribe(this.info.hostname$)).add(t.providerOutput.httpConnectionType$.pipe(e.filterChanged()).subscribe(this.info.httpConnectionType$)).add(t.providerOutput.httpConnectionReused$.pipe(e.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(t.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(t.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(t.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(t.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(t.providerOutput.duration$.subscribe(this.info.duration$)).add(t.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(t.providerOutput.isLive$.subscribe(this.info.isLive$)).add(t.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(t.providerOutput.volume$.pipe(e.map((e=>e.muted)),e.filterChanged()).subscribe(this.info.muted$)).add(t.providerOutput.volume$.pipe(e.map((e=>e.volume)),e.filterChanged()).subscribe(this.info.volume$)).add((({seekState:t,position$:s})=>e.merge(t.stateChangeEnded$.pipe(e.map((({to:e})=>e.state===h.None?void 0:(e.position??NaN)/1e3)),e.filter(e.isNonNullable)),s.pipe(e.filter((()=>t.getState().state===h.None)))))({seekState:this.desiredState.seekState,position$:t.providerOutput.position$}).subscribe(this.info.position$)).add(e.merge(t.providerOutput.endedEvent$.pipe(e.mapTo(!0)),t.providerOutput.seekedEvent$.pipe(e.mapTo(!1))).pipe(e.filterChanged()).subscribe(this.info.isEnded$)).add(t.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(t.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(t.providerError$.subscribe(this.events.managedError$)).add(t.noAvailableProvidersError$.pipe(e.map((e=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(t.providerOutput.element$.subscribe(this.experimental.element$)).add(t.providerOutput.firstBytesEvent$.subscribe(this.events.firstBytes$)).add(t.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const s=new e.ValueSubject(!1);this.subscription.add(t.providerOutput.seekedEvent$.subscribe((()=>s.next(!1)))).add(t.providerOutput.willSeekEvent$.subscribe((()=>s.next(!0))));const i=new e.ValueSubject(!0);this.subscription.add(t.current$.subscribe((()=>i.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((({to:e})=>e===exports.PlaybackState.PLAYING)),e.once()).subscribe((()=>i.next(!1))));let a=0;const r=e.merge(t.providerOutput.isBuffering$,s,i).pipe(e.map((()=>{const e=t.providerOutput.isBuffering$.getValue(),a=s.getValue()||i.getValue();return e&&!a})),e.filterChanged());this.subscription.add(r.subscribe((e=>{e?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const o=new e.Subscription;this.subscription.add(o);const n=e.merge(e.fromEvent(window,'beforeunload'),this.events.willDestruct$,t.current$.pipe(e.filter((e=>Boolean(e?.provider)))));t.providerOutput.isLive$.pipe(e.filterChanged()).subscribe((t=>{switch(e.assertNonNullable(this.providerContainer),o.unsubscribe(),t){case!0:o.add(as({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:o.add(is({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(e.map((e=>e?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const s=new e.Subscription;this.subscription.add(s),this.subscription.add(t.current$.pipe(e.filterChanged(((e,t)=>e.provider===t.provider))).subscribe((()=>{s.unsubscribe(),s.add(t.providerOutput.availableVideoTracks$.pipe(e.filter((e=>e.length>0)),e.once()).subscribe((e=>{this.setStartingVideoTrack(e)})))})))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find((({quality:e})=>e===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),t||(t=ne(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(e.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'playbackState',type:'end'}))))).pipe(e.map((e=>({component:'desiredState',message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const t=this.providerContainer?.providerOutput;e.assertNonNullable(this.providerContainer),e.assertNonNullable(t),se={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((e=>{te=e})),this.providerContainer.current$.subscribe((({type:e})=>ae('provider',e))),t.duration$.subscribe((e=>ae('duration',e))),t.availableVideoTracks$.pipe(e.filter((e=>!!e.length)),e.once()).subscribe((e=>ae('tracks',e))),this.events.fatalError$.subscribe(new re('fatalError')),this.events.managedError$.subscribe(new re('managedError')),t.position$.subscribe(new re('position')),t.currentVideoTrack$.pipe(e.map((e=>e?.quality))).subscribe(new re('quality')),t.currentBuffer$.subscribe(new re('buffer')),t.isBuffering$.subscribe(new re('isBuffering'))].forEach((e=>this.subscription.add(e))),ae('codecs',Object.keys(Nt).filter((e=>Nt[e])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.49';
|
|
6
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var e=require('@vkontakte/videoplayer-shared/esnext.cjs.js');function t(e){return e&&'object'==typeof e&&'default'in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if('default'!==s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var i=t(require('lodash/debounce'));var a,r,o,n,d,u,h;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_VK',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM_VK',r.DASH_ONDEMAND='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_JS',r.HLS_LIVE='HLS_LIVE',function(e){e.SCREEN='SCREEN',e.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.StartStatus=void 0,(d=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',d.SuccessWithoutSound='success_without_sound',d.Failed='failed',exports.HttpConnectionType=void 0,(u=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',u.HTTP2='http2',u.QUIC='quic',function(e){e.None='none',e.Requested='requested',e.Applying='applying'}(h||(h={}));class c{connection$=new e.ValueSubject(void 0);castState$=new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new e.Subject;contentId;realCastState$=new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new e.Subscription;log;params;constructor(t){this.params=t,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}`}),t.isDisabled||!s)return;var i;e.isNonNullable(window.chrome?.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{e&&this.initializeCastApi()},(i='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((e,t)=>{const s=document.createElement('script');s.setAttribute('src',i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)}))}toggleConnection(){e.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const s=this.connection$.getValue();e.isNullable(s)||(s.remotePlayer.volumeLevel=t,s.remotePlayerController.setVolumeLevel())}setMuted(t){const s=this.connection$.getValue();e.isNullable(s)||t!==s.remotePlayer.isMuted&&s.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,s=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(e.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return e.assertNever(t.sessionState)}}))).add(e.merge(e.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(e.tap((e=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(e)}`})})),e.map((e=>e.castState))),e.observableFrom([i.getCastState()])).pipe(e.filterChanged(),e.map(l),e.tap((e=>{this.log({message:`realCastState$: ${e}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{const r=a===exports.ChromecastState.CONNECTED,o=e.isNonNullable(this.connection$.getValue());if(r&&!o){const a=i.getCurrentSession();e.assertNonNullable(a);const r=a.getCastDevice(),o=a.getMediaSession()?.media.contentId;(e.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:s,session:a,castDevice:r}))}else!r&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?e.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)})))}initializeCastApi(){let e,t,s;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(e){return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(e){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:e})}}}const l=t=>{switch(t){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 e.assertNever(t)}};var p;!function(e){e[e.OFFSET_P=0]='OFFSET_P',e[e.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(p||(p={}));var m,S=(t,s=0,i=p.OFFSET_P)=>{switch(i){case p.OFFSET_P:return t.replace('_offset_p',0===s?'':'_'+s.toFixed(0));case p.PLAYBACK_SHIFT:{if(0===s)return t;const e=new URL(t);return e.searchParams.append('playback_shift',s.toFixed(0)),e.toString()}default:e.assertNever(i)}return t},f=(e,t,s=!1)=>{const i=e.getTransition();!s&&i&&i.to!==t||e.setState(t)};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}},g=(e,t)=>b[e].height>b[t].height,v=(e,t)=>b[e].height<b[t].height,y=Object.keys(b).sort(((e,t)=>v(e,t)?-1:1)),T=({width:e,height:t})=>{const s=Math.min(e,t),i=Math.max(e,t);return y.find((e=>{const t=b[e];return t.width>=i&&t.height>=s}))},E=e=>e===exports.VideoQuality.INVARIANT;class k{state;transition;transitionStarted$=new e.Subject;transitionEnded$=new e.Subject;transitionUpdated$=new e.Subject;forceChanged$=new e.Subject;stateChangeStarted$=e.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=e.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(t){const s=this.transition,i=this.state;i===t||e.isNonNullable(s)&&s.to===t||(this.state=t,s?(this.transition={from:s.from,to:t,canceledTransition:s},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var $;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}($||($={}));class P{subscription=new e.Subscription;loadMediaTimeoutSubscription=new e.Subscription;videoState=new k($.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:return!0;default:return e.assertNever(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const s=this.params.connection.session.getMediaSession();s&&this.restoreSession(s),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new e.Subscription;this.subscription.add(t),this.subscription.add(e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>`stateChangeStarted$ ${JSON.stringify(e)}`))),this.videoState.stateChangeEnded$.pipe(e.map((e=>`stateChangeEnded$ ${JSON.stringify(e)}`)))).subscribe((e=>this.log({message:`[videoState] ${e}`}))));const s=(e,t)=>this.subscription.add(e.subscribe(t));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new e.Subject;t.add(s.pipe(e.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let i=NaN;t.add(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((e=>{this.logRemoteEvent(e);const t=e.value;this.params.output.position$.next(t);(this.params.desiredState.seekState.getState().state===h.Applying||Math.abs(t-i)>5)&&s.next(t),i=t}))),t.add(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((e=>{this.logRemoteEvent(e),this.params.output.duration$.next(e.value)})))}s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemotePause():this.handleRemotePlay()})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:s}=this.params.connection,i=t.value,a=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),f(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:e.assertNever(i)}})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({volume:e.value})})),s(e.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({muted:e.value})}));s(e.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)),this.syncPlayback)}restoreSession(e){this.log({message:'restoreSession'});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState($.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState($.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const e=this.params.output.isLive$.getValue();this.params.output.duration$.next(e?0:t.duration),this.params.output.position$.next(e?0:t.currentTime),this.params.desiredState.seekState.setState({state:h.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==$.PAUSED&&e!==$.PLAYING||(this.videoState.setState($.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==$.PLAYING&&e!==$.PAUSED||(this.videoState.setState($.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===$.READY&&this.videoState.setState($.READY)}handleRemoteStop(){this.videoState.getState()!==$.STOPPED&&this.videoState.setState($.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),s={volume:e.volume??t.volume,muted:e.muted??t.muted};s.volume===t.volume&&s.muted==s.muted||this.params.output.volume$.next(s)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(t){const s=this.params.source;let i,a,r;switch(t){case exports.VideoFormat.MPEG:{const o=s[t];e.assertNonNullable(o);const n=Object.keys(o).sort(((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:v(e,t)?1:-1))[0];e.assertNonNullable(n);const d=o[n];e.assertNonNullable(d),i=d,a='video/mp4',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/x-mpegurl',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/dash+xml',r=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const o=s[t];e.assertNonNullable(o),i=S(o.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const o=s[t];e.assertNonNullable(o),i=o.url,a='application/dash+xml',r=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:{const e='Unsupported format for Chromecast',t=new Error(e);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:e,thrown:t}),t}default:return e.assertNever(t)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);o.contentUrl=i,o.streamType=r,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:n,subtitle:d}=this.params.meta;return e.isNonNullable(n)&&(o.metadata.title=n),e.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===h.Applying||s.state===h.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(t){const s=this.params.connection.session.loadMedia(t),i=new Promise(((t,s)=>{this.loadMediaTimeoutSubscription.add(e.timeout(7e3).subscribe((()=>s('timeout(7000)'))))}));Promise.race([s,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===h.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(e=>{const t=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:t}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:t,thrown:e})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i!==exports.PlaybackState.STOPPED){if(!s)if(a?.to===exports.PlaybackState.PAUSED||r.state!==h.Requested||t===$.STOPPED)switch(i){case exports.PlaybackState.PLAYING:switch(t){case $.PLAYING:break;case $.PAUSED:case $.READY:this.videoState.startTransitionTo($.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case $.STOPPED:this.videoState.startTransitionTo($.READY),this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case $.PLAYING:this.videoState.startTransitionTo($.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case $.PAUSED:break;case $.READY:this.videoState.startTransitionTo($.PAUSED),this.videoState.setState($.PAUSED);break;case $.STOPPED:this.videoState.startTransitionTo($.READY),this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(i)}else this.seek(r.position)}else t!==$.STOPPED&&(this.videoState.startTransitionTo($.STOPPED),this.stop())}}class w{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let e=0,i=s.length;e<i;e++)if(s[e].callback===t)return void s.splice(e,1)}dispatchEvent(e){if(!(e.type in this.listeners))return;const t=this.listeners[e.type].slice();for(let s=0,i=t.length;s<i;s++){const i=t[s];try{i.callback.call(this,e)}catch(e){Promise.resolve().then((()=>{throw e}))}i.options&&i.options.once&&this.removeEventListener(e.type,i.callback)}return!e.defaultPrevented}}class A extends w{constructor(){super(),this.listeners||w.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(e){'abort'===e.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class x{constructor(){Object.defineProperty(this,'signal',{value:new A,writable:!0,configurable:!0})}abort(){let e;try{e=new Event('abort')}catch(t){'undefined'!=typeof document?document.createEvent?(e=document.createEvent('Event'),e.initEvent('abort',!1,!1)):(e=document.createEventObject(),e.type='abort'):e={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(e)}toString(){return'[object AbortController]'}}function N(e){return e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof e.Request&&!e.Request.prototype.hasOwnProperty('signal')||!e.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(x.prototype[Symbol.toStringTag]='AbortController',A.prototype[Symbol.toStringTag]='AbortSignal');const _=N({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),D=_?function(e){'function'==typeof e&&(e={fetch:e});const{fetch:t,Request:s=t.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=e;if(!N({fetch:t,Request:s,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:t,Request:r};let r=s;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(e,t){let i;t&&t.signal&&(i=t.signal,delete t.signal);const a=new s(e,t);return i&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:i}),a},r.prototype=s.prototype);const o=t;return{fetch:(e,t)=>{const s=r&&r.prototype.isPrototypeOf(e)?e.signal:t?t.signal:void 0;if(s){let i;try{i=new DOMException('Aborted','AbortError')}catch(e){i=new Error('Aborted'),i.name='AbortError'}if(s.aborted)return Promise.reject(i);const a=new Promise(((e,t)=>{s.addEventListener('abort',(()=>t(i)),{once:!0})}));return t&&t.signal&&delete t.signal,Promise.race([a,o(e,t)])}return o(e,t)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,R=_?D.fetch:window.fetch;_?D.Request:window.Request;const I=_?x:window.AbortController,C=e=>e.range?e.range.split('-').map((e=>parseInt(e,10))):[NaN,NaN];class L{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[a,r]=C(i.request);if(a>=s.from&&r<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map((({request:e})=>e)));this.activeRequests.set(e,s)}}}abort(e){if(e){const{request:t}=e,s=(this.dashJsRequestQueue.get(t.url)??[]).includes(e),i=this.activeRequests.get(t.url);s&&i&&i.abortController.abort()}else for(const{abortController:e}of this.activeRequests.values())e.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(C),i=s[0][0];let a=s[0][1];for(let e=1;e<s.length&&a<this.params.minDataSize;e++){const t=s[e][1];t-i<=2*this.params.minDataSize&&(a=Math.max(a,t))}a=0===i?Math.max(a,i+this.params.minInitSize):Math.max(a,i+this.params.minDataSize);const r=new URL(e,location.href);r.searchParams.append('bytes',`${i}-${a}`);const o=r.toString(),n=new I,d=n.signal,u={url:e,from:i,to:a,loaded:0,data:null,abortController:n};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=e=>{throw this.params.onError?.({id:'BigRequestParsing',message:'Error parsing response data',thrown:e}),e};return R(o,{signal:d}).then((e=>{if(!e.ok||!e.body)return void this.onBigRequestError(u);const[t,s]=e.body.tee();this.params.onDownloadStream?.(s);const i=t.getReader(),a=parseInt(e.headers.get('Content-Length')??'',10);u.data=new ArrayBuffer(a);const r=new Uint8Array(u.data),o=async({done:e,value:t})=>{e?this.onBigRequestProgress(u):t&&(r.set(t,u.loaded),u.loaded+=t.byteLength,this.onBigRequestProgress(u),await(i?.read().then(o,L.suppressStreamErrors).catch(h)))};i?.read().then(o,L.suppressStreamErrors).catch(h)}),L.suppressAbort).catch((e=>this.onBigRequestError(u,e))),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a}){if(!this.activeRequests.has(e)||!a)return;const r=this.dashJsRequestQueue.get(e)??[];for(const o of r){const{request:r}=o,[n,d]=C(r),u=n>=t&&d<=t+i,h=t>=n&&t+i<d,c=a.slice(n-t,Math.min(d-t+1,i));(u||h)&&(r.requestStartDate=r.requestStartDate??new Date,r.firstByteDate=r.firstByteDate??new Date,r.bytesLoaded=c.byteLength,r.bytesTotal=s-t),u?(r.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter((e=>e!==o))),o.success?.(c,'',e),this.dashMetrics?.addHttpRequest(r,e,200,{},[])):h&&o.progress?.({loaded:i,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},i){if(this.params.onError?.({id:'BigRequest',message:'Download error',thrown:i}),!this.activeRequests.has(e))return;const a=this.dashJsRequestQueue.get(e)??[];for(const e of a){const[a,r]=C(e.request);(a>=t&&a<s||r>t&&r<=s)&&e?.error?.(e.request,String(i))}if(this.activeRequests.delete(e),i)throw i}onBigRequestAbort({url:e,from:t,to:s}){if(!this.activeRequests.has(e))return;const i=this.dashJsRequestQueue.get(e)??[];for(const e of i){const[i,a]=C(e.request);(i>=t&&i<s||a>t&&a<=s)&&e?.abort?.(e.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e}static suppressStreamErrors(){}}class B{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return'download'!==e.action||'text'===e.mediaType||!e.range||'arraybuffer'!==e.responseType}load(e){const{request:t}=e;if(B.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:t}=e;B.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const O=(e,t)=>{const s=new L(t);return e.extend('SchemeLoaderFactory',(function(){const{parent:e}=this,t=e.getLoader;return{getLoader:e=>((e,t)=>s=>({create:i=>{const a=e(s).create(i);return new B(a,t,i)}}))(t(e),s)}}),!0),()=>s.destroy()};var V=e=>{let t,s=!1,i=!1;e.on('playbackTimeUpdated',(({timeToEnd:e})=>{i=e<=3,s&&i&&t?.()})),e.extend('MediaSourceController',(function(){const{parent:e}=this,a=e.signalEndOfStream;return{signalEndOfStream:e=>{s=!0,t=()=>a(e),s&&i&&t?.()}}}),!0)},M=t=>{const s=new e.ValueSubject(1/0),i=new e.Subject;let a=NaN,r=!1;return t.extend('XHRLoader',(function(){const{parent:t}=this,o=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const o=t.onload,n=t.progress;t.onload=function(...t){return(t=>{if(!t.getAllResponseHeaders().includes('x-playback-duration'))return;const i=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),a=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*i??NaN;e.isNonNullable(a)&&!isNaN(a)&&s.next(a)})(this),o(...t)},t.progress=function(...e){return this.readyState>=2&&!r&&(r=!0,i.next(Date.now()-a)),n(...e)},a=Date.now(),r=!1}return o(t)}}}),!0),{playbackDuration$:s,ping$:i}},F=e=>{const t=new URL(e);return t.searchParams.append('quic','1'),t.toString()},U=e=>{e.extend('HTTPLoader',(function(){const{parent:e}=this,t=e.load;return{load:e=>{if(e.request&&e.request.range){const[t,s]=e.request.range.split('-').map((e=>parseInt(e,10))),i=new URL(e.request.url,location.href);i.searchParams.append('bytes',`${t}-${s}`),e.request.url=i.toString(),e.request.range=void 0}t(e)}}}),!0)};const q=(t,s,i,{equal:a=((e,t)=>e===t),changed$:r,onError:o}={})=>{const n=t.getState(),d=s(),u=e.isNullable(r),h=new e.Subscription;return r&&h.add(r.subscribe((e=>{const s=t.getState();a(e,s)&&t.setState(e)}),o)),a(d,n)||(i(n),u&&t.setState(n)),h.add(t.stateChangeStarted$.subscribe((e=>{i(e.to),u&&t.setState(e.to)}),o)),h},H=(t,s,i)=>q(s,(()=>t.loop),(s=>{e.isNonNullable(s)&&(t.loop=s)}),{onError:i}),j=(t,s,i,a)=>q(s,(()=>({muted:t.muted,volume:t.volume})),(s=>{e.isNonNullable(s)&&(t.muted=s.muted,t.volume=s.volume)}),{equal:(e,t)=>e===t||e?.muted===t?.muted&&e?.volume===t?.volume,changed$:i,onError:a}),G=(e,t)=>{if(e.id===t)return!0;const[s,i,a]=t.split('|');return e.language===i&&e.label===a};class Y{available$=new e.Subject;current$=new e.ValueSubject(void 0);error$=new e.Subject;video;cueSettings;subscription=new e.Subscription;externalTracks=new Map;connect(t,s,i){this.video=t,this.cueSettings=s.textTrackCuesSettings,this.subscribe();const a=e=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:e})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(q(s.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{e.isNonNullable(t)&&this.setExternal(t)}),{equal:(t,s)=>e.isNonNullable(t)&&e.isNonNullable(s)&&t.length===s.length&&t.every((({id:e},t)=>e===s[t].id)),changed$:this.available$.pipe(e.map((e=>e.filter((({type:e})=>'external'===e))))),onError:a})),this.subscription.add(q(s.currentTextTrack,(()=>{if(this.video)return;const e=this.htmlTextTracksAsArray().find((({mode:e})=>'showing'===e));return e&&this.htmlTextTrackToITextTrack(e).id}),(e=>this.select(e)),{changed$:this.current$,onError:a})),this.subscription.add(q(s.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const e of this.htmlTextTracksAsArray())this.applyCueSettings(e.cues),this.applyCueSettings(e.activeCues)})))}subscribe(){e.assertNonNullable(this.video);const{textTracks:t}=this.video;this.subscription.add(e.fromEvent(t,'addtrack').subscribe((()=>{const e=this.current$.getValue();this.select(e)}))),this.subscription.add(e.merge(e.fromEvent(t,'addtrack'),e.fromEvent(t,'removetrack'),e.observableFrom(['init'])).pipe(e.map((()=>this.htmlTextTracksAsArray().map((e=>this.htmlTextTrackToITextTrack(e))))),e.filterChanged(((e,t)=>e.length===t.length&&e.every((({id:e},s)=>e===t[s].id))))).subscribe(this.available$)),this.subscription.add(e.merge(e.fromEvent(t,'change'),e.observableFrom(['init'])).pipe(e.map((()=>this.htmlTextTracksAsArray().find((({mode:e})=>'showing'===e)))),e.map((e=>e&&this.htmlTextTrackToITextTrack(e).id)),e.filterChanged()).subscribe(this.current$));const s=e=>this.applyCueSettings(e.target?.activeCues??null);this.subscription.add(e.fromEvent(t,'addtrack').subscribe((e=>{e.track?.addEventListener('cuechange',s);const t=e=>{const s=e.target?.cues??null;s&&s.length&&(this.applyCueSettings(e.target?.cues??null),e.target?.removeEventListener('cuechange',t))};e.track?.addEventListener('cuechange',t)}))),this.subscription.add(e.fromEvent(t,'removetrack').subscribe((e=>{e.track?.removeEventListener('cuechange',s)})))}applyCueSettings(t){if(!t||!t.length)return;const s=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;e.isNonNullable(s.align)&&(t.align=s.align),e.isNonNullable(s.position)&&(t.position=s.position),e.isNonNullable(s.size)&&(t.size=s.size),e.isNonNullable(s.line)&&(t.line=s.line)}}htmlTextTracksAsArray(t=!1){e.assertNonNullable(this.video);const s=[...this.video.textTracks];return t?s:s.filter(Y.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=''!==e.id?e.id:(e=>['__',e.language,e.label].join('|'))(e);return this.externalTracks.has(i)?{id:i,type:'external',language:t,label:s,url:this.externalTracks.get(i).url}:{id:i,type:'internal',language:t,label:s}}static isHealthyTrack(e){return'metadata'!==e.kind&&(''!==e.id||''!==e.label||''!==e.language)}setExternal(e){e.filter((({id:e})=>!this.externalTracks.has(e))).forEach((e=>this.attach(e))),Array.from(this.externalTracks.keys()).filter((t=>!e.find((e=>e.id===t)))).forEach((e=>this.detach(e)))}select(t){e.assertNonNullable(this.video);for(const s of this.htmlTextTracksAsArray(!0))e.isNonNullable(t)&&G(s,t)?s.mode='showing':s.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName('track'))){const t=e.getAttribute('id');t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(t){e.assertNonNullable(this.video);const s=document.createElement('track');s.setAttribute('src',t.url),s.setAttribute('id',t.id),t.label&&s.setAttribute('label',t.label),t.language&&s.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(s)}detach(t){e.assertNonNullable(this.video);const s=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));s&&this.video.removeChild(s),this.externalTracks.delete(t)}}var Q=e=>{const t=document.createElement('video');return t.setAttribute('crossorigin','anonymous'),t.setAttribute('playsinline','playsinline'),e.appendChild(t),t};class z{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var W=t=>new e.Observable((s=>{let i=0;return(new e.Subscription).add(e.fromEvent(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(e.fromEvent(t,'loadeddata').subscribe((()=>{s.next(Date.now()-i)})))})).pipe(e.once());class J{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let s=this._source.buffered.start(t);const i=this._source.buffered.end(t);s>e&&s-e<3&&(s=e),this._buffer.push({start:s,end:i,i:t})}return this._buffer.sort((function(e,t){return e.start-t.start})),this._buffer}getByTime(e){return this._buffer.find((t=>e>=t.start&&e<t.end))}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.start-e.end<(t||3))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach((({start:i,end:a})=>{const r=i>=e&&i<t,o=a>=e&&a<t;r&&o||(r?s(t,a):o?s(i,e):i<e&&a>t?(s(t,a),s(i,e)):s(i,a))}))}destroy(){this._buffer=[]}}var K=(e,t,s=3)=>{let i=0,a=0;for(let r=0;r<e.length;r++){const o=e.start(r),n=e.end(r);if(o<=t&&t<=n){if(i=o,a=n,!s)return{start:i,end:a};for(let t=r-1;t>=0;t--)e.end(t)+s>=i&&(i=e.start(t));for(let t=r+1;t<e.length;t++)e.start(t)-s<=a&&(a=e.end(t))}}return{start:i,end:a}},X=t=>new e.Observable((s=>{let i=0;return(new e.Subscription).add(e.fromEvent(t,'loadstart').subscribe((()=>{i=Date.now()}))).add(e.fromEvent(t,'loadedmetadata').subscribe((()=>{s.next(Date.now()-i)})))})).pipe(e.once());const Z=t=>{const s=(s,i=(()=>{}))=>e.fromEvent(t,s).pipe(e.map(i)),i=e.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((s=>e.fromEvent(t,s)))).pipe(e.map((()=>t.readyState<3)),e.filterChanged()),a=e.merge(e.fromEvent(t,'progress'),e.fromEvent(t,'timeupdate')).pipe(e.map((()=>K(t.buffered,t.currentTime)))),r=e.fromEvent(t,'volumechange').pipe(e.debounce(0),e.map((()=>({muted:t.muted,volume:t.volume})))),o=e.fromEvent(t,'error').pipe(e.map((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),n=s('timeupdate',(()=>t.currentTime)),d=new e.Subject;let u;return n.subscribe((s=>{t.loop&&e.isNonNullable(u)&&e.isNonNullable(s)&&u>=t.duration-.3&&s<=.3&&d.next(u),u=s})),{playing$:s('playing'),pause$:s('pause'),canplay$:s('canplay'),ended$:s('ended'),looped$:d,error$:o,seeked$:s('seeked'),seeking$:s('seeking'),progress$:s('progress'),loadedMetadata$:s('loadedmetadata'),loadedData$:s('loadeddata'),timeUpdate$:n,durationChange$:s('durationchange',(()=>t.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:r,firstBytes$:X(t),firstFrame$:W(t)}},ee=e=>{if(e.includes('/')){const t=e.split('/');return parseInt(t[0])/parseInt(t[1])}return parseFloat(e)};let te=!1,se={};const ie=e=>{e(se)},ae=(e,t)=>{te&&(se.meta=se.meta??{},se.meta[e]=t)};class re{name;constructor(e){this.name=e}next(e){if(!te)return;se.series=se.series??{};const t=se.series[this.name]??[];t.push([Date.now(),e]),se.series[this.name]=t}}const oe=new re('best_bitrate'),ne=(t,{container:s,throughput:i,tuning:a,limits:r,forwardBufferHealth:o,currentRepresentation:n})=>{const d=a.usePixelRatio?window.devicePixelRatio??1:1,u=a.limitByContainer&&s&&s.width>0&&s.height>0&&{width:s.width*d*a.containerSizeFactor,height:s.height*d*a.containerSizeFactor},h=u&&T(u),c=t.filter((e=>!E(e.quality))).sort(((e,t)=>g(e.quality,t.quality)?-1:1)),l=c.at(-1)?.quality,p=c.at(0)?.quality,m=e.isNullable(r)||e.isNonNullable(r.min)&&e.isNonNullable(r.max)&&v(r.max,r.min)||e.isNonNullable(r.min)&&p&&g(r.min,p)||e.isNonNullable(r.max)&&l&&v(r.max,l),S=c.filter((t=>{const s=!h||v(t.quality,h),d=!(e.isNonNullable(i)&&isFinite(i)&&e.isNonNullable(t.bitrate))||i>=t.bitrate*(u=o??.5,c=a.bitrateFactorAtEmptyBuffer,l=a.bitrateFactorAtFullBuffer,(c-l)*Math.pow(2,-10*u)+l);var u,c,l;const p=!a.lazyQualitySwitch||!n||(o??.5)>=.5||(t.size?.height||0)<=(n?.height||0),S=m||(e.isNullable(r.max)||(f=t.quality,g=r.max,b[f].height<=b[g].height))&&(e.isNullable(r.min)||((e,t)=>b[e].height>=b[t].height)(t.quality,r.min));var f,g;return s&&d&&p&&S}))[0];return S&&S.bitrate&&oe.next(S.bitrate),S??c[Math.ceil((c.length-1)/2)]??t[0]};var de=e=>new URL(e).hostname;const ue=(t,s=300)=>new e.Observable((a=>{const{width:r,height:o}=t.getBoundingClientRect();if(a.next({width:r,height:o}),!window.ResizeObserver)return;const n=new ResizeObserver(i.default((t=>{const s=t[0];if(!s)return;let i,r;s.contentBoxSize&&s.contentBoxSize[0]?(r=s.contentBoxSize[0].blockSize,i=s.contentBoxSize[0].inlineSize):s.contentRect&&(i=s.contentRect.width,r=s.contentRect.height),e.isNonNullable(i)&&e.isNonNullable(r)&&a.next({width:i,height:r})}),s));return n.observe(t),()=>n.disconnect()})),he={};var ce;!function(e){e.DOWNLOADING_LIB='downloading_lib',e.STOPPED='stopped',e.STREAM_INITIALIZED='stream_initialized',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ce||(ce={}));const le=(t,s)=>new e.Observable((e=>{const i=t=>e.next(t);return t.on(s,i),()=>t.off(s,i)}));class pe{subscription=new e.Subscription;videoState=new k(ce.DOWNLOADING_LIB);video;player;params;textTracksManager=new Y;videoTracks=[];frameRatesByFrameHeight={};isLive$=new e.ValueSubject(void 0);maxSeekBackTime$=new e.ValueSubject(1/0);availableFrom$=new e.ValueSubject(void 0);elementSize$=new e.ValueSubject(void 0);liveOffset=new z;destroyBigRequest;constructor(e){this.video=Q(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=t=>{e||this.params.output.error$.next({id:'timeout'===t?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${t?.toString?.()}`,thrown:t}),e=!0},i=window.setTimeout((()=>t('timeout')),5e3);Promise.resolve().then((function(){return s(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((t=>{e||(he.MediaPlayer=t.MediaPlayer,he.Debug=t.Debug,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(he.MediaPlayer,'dashjs not loaded'),e.assertNonNullable(he.Debug,'dashjs not loaded'),this.player=he.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((e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?ee(e.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=O(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:e=>this.params.output.error$.next(e),onDownloadStream:e=>this.params.dependencies.throughputEstimator.trackStream(e)}):this.params.tuning.stripRangeHeader&&U(this.player),V(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:F})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(ce.STOPPED)}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(e,t)=>this.subscription.add(e.subscribe(t,i));a(ue(this.video),this.elementSize$),a(le(this.player,'error').pipe(e.map((e=>({id:`DashJS#${'object'==typeof e.error?e.error.code:e.error}`,message:'object'==typeof e.error?e.error.message:void 0})))),t.error$),a(le(this.player,'playbackError').pipe(e.map((e=>({id:'DashJSPlayback',message:e.error})))),t.error$);const r=le(this.player,'qualityChangeRendered').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({newQuality:e})=>this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===e))?.track)));r.pipe(e.filter(e.isNonNullable)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(e.filter((({to:e})=>e===ce.STREAM_INITIALIZED)),e.once()).subscribe((()=>{this.subscription.add(q(s.videoTrack,(()=>{const e=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===e))?.track?.id}),(t=>{if(e.isNullable(t))return;const s=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(e.map((e=>e?.id))),onError:i}))}),i)),this.subscription.add(q(s.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(e=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:e}}}})),{onError:i})),a(le(this.player,'bufferStateChanged').pipe(e.filter((({mediaType:e})=>'video'===e)),e.map((({state:e})=>'bufferStalled'===e))),t.isBuffering$),a(le(this.player,'fragmentLoadingStarted').pipe(e.map((e=>de(e.request.url)))),t.hostname$),a(le(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:s,availableFrom:i}}})=>{this.isLive$.next(s),this.availableFrom$.next(i.getTime()),s||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const e of this.player.getBitrateInfoListFor('video')){const t=e.qualityIndex.toString(10),s=T(e),i=e.bitrate/1e3,o={width:e.width,height:e.height},n=this.frameRatesByFrameHeight[e.height];if(s){const d={id:t,quality:s,bitrate:i,size:o,fps:n};this.videoTracks.push({track:d,bitrateInfo:e}),e.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:e})=>e))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(ce.STREAM_INITIALIZED),this.videoState.startTransitionTo(ce.READY)})),a(le(this.player,'fragmentLoadingCompleted'),(({request:e})=>{if(!e.requestEndDate||!e.firstByteDate||!e.bytesLoaded)return;const t=e.requestEndDate.getTime()-e.firstByteDate.getTime(),s=e.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(s,t)})),a(e.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,s.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const e=this.params.dependencies.throughputEstimator.throughput$.getValue(),t=ne(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:e,tuning:this.params.tuning.autoTrackSelection,limits:s.autoVideoTrackLimits.getState()}),i=this.videoTracks.find((({track:e})=>e===t));i?.bitrateInfo&&this.player.setQualityFor('video',i?.bitrateInfo.qualityIndex,!1)})),a(e.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(e.filter(e.isNonNullable))}).pipe(e.filter((({isLive:e})=>e)),e.map((({maxSeekBackTime:e})=>-e/1e3))),this.params.output.duration$);const o=le(this.player,'playbackTimeUpdated').pipe(e.map((({time:e})=>e??0)));a(e.combine({availableFrom:this.availableFrom$.pipe(e.filter(e.isNonNullable)),currentTime:o}),(({availableFrom:e,currentTime:t})=>this.params.output.liveTime$.next(e+1e3*t))),a(o.pipe(e.filter((()=>!1===this.isLive$.getValue()))),t.position$),a(le(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(le(this.player,'playbackEnded'),t.endedEvent$),a(le(this.player,'playbackProgress').pipe(e.map((()=>K(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(le(this.player,'playbackPlaying'),(()=>{this.videoState.setState(ce.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)})),a(le(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(ce.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(le(this.player,'playbackPaused'),(()=>{this.videoState.setState(ce.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)})),a(le(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY)})),a(this.isLive$,t.isLive$),a(ue(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)),this.syncPlayback);const{playbackDuration$:n,ping$:d}=M(this.player);a(n,this.maxSeekBackTime$),a(d.pipe(e.once()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&a(e.combine({isLive:this.isLive$,isShort:t.duration$.pipe(e.map((e=>e<60)))}),(({isLive:e,isShort:t})=>{const s=!e&&t;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:s}}})})),a(o.pipe(e.filter((e=>e>this.params.tuning.insufficientBufferRuleMargin)),e.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,s,t),this.subscription.add(le(this.player,'manifestLoaded').pipe(e.once()).subscribe((()=>{const s=Date.now();this.subscription.add(le(this.player,'playbackPlaying').pipe(e.once()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-s)),i))}),i)),this.subscription.add(H(this.video,s.isLooped,i));const{volumeState$:u,looped$:h}=Z(this.video);this.subscription.add(j(this.video,s.volume,u,i)),this.subscription.add(u.subscribe(t.volume$,i)),this.subscription.add(h.subscribe(t.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(ce.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(ce.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const i=S(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,p.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(ce.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==ce.DOWNLOADING_LIB&&t!==ce.STREAM_INITIALIZED)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===h.Requested&&t!==ce.STOPPED&&s!==exports.PlaybackState.STOPPED&&(r?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case exports.PlaybackState.STOPPED:switch(t){case ce.STOPPED:break;case ce.PLAYING:case ce.PAUSED:case ce.READY:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case ce.PLAYING:break;case ce.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 ce.READY:this.play();break;case ce.STOPPED:this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case ce.PLAYING:this.pause(),this.liveOffset.pause();break;case ce.PAUSED:break;case ce.READY:this.videoState.setState(ce.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case ce.STOPPED:this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(e){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var me=e=>{switch(e){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}},Se=async e=>{const t=e.muted;try{await e.play()}catch(s){if(s instanceof DOMException&&(20===s.code||'AbortError'===s.name))return!1;if(t)return console.warn(s),!1;e.muted=!0;try{await e.play()}catch(t){return e.muted=!1,console.warn(t),!1}}return!0};function fe(){return e.now()}function be(e){return fe()-e}function ge(e){const t=e.split('/'),s=t.slice(0,t.length-1).join('/'),i=/^([a-z]+:)?\/\//i;return{resolve:(e,t,a=!1)=>{(e=>i.test(e))(e)||(e.startsWith('/')||(e='/'+e),e=s+e);let r=e.indexOf('?')>-1?'&':'?';return a&&(e+=r+'lowLat=1',r='&'),t&&(e+=r+'_rnd='+Math.floor(999999999*Math.random())),e}}}function ve(t,s,i,a){const r=window.XMLHttpRequest;let o,n,d,u,h,c=!1,l=0,p=!1,m='arraybuffer',S=7e3,f=2e3,b=()=>{if(c)return;e.assertNonNullable(u);const t=be(u);let s;if(t<f)return s=f-t,void setTimeout(b,s);f*=2,f>S&&(f=S),n&&n.abort(),n=new r,v()};const g=()=>{if(!c){if(--l>=0)return b(),void(a&&a());c=!0,h&&h(),i&&i()}},v=()=>{u=fe(),n=new r,n.open('get',t);let i,a=0,l=0;const S=()=>(e.assertNonNullable(u),Math.max(u,Math.max(i||0,l||0)));if(o&&n.addEventListener('progress',(e=>{const t=fe();o.updateChunk&&e.loaded>a&&(o.updateChunk(S(),e.loaded-a),a=e.loaded,i=t)})),d&&(n.timeout=d,n.addEventListener('timeout',(()=>g()))),n.addEventListener('load',(()=>{if(c)return;e.assertNonNullable(n);const t=n.status;if(t>=200&&t<300){if(n.response.byteLength&&o){const e=n.response.byteLength-a;e&&o.updateChunk&&o.updateChunk(S(),e)}h&&h(),n&&s(n.response)}else g()})),n.addEventListener('error',(()=>{g()})),p){const t=()=>{e.assertNonNullable(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(l=fe(),n.removeEventListener('readystatechange',t))};n.addEventListener('readystatechange',t)}return n.responseType=m,n.send(),y},y={withBitrateReporting:e=>(o=e,y),withParallel:e=>(p=e,y),withJSONResponse:()=>(m='json',y),withRetryCount:e=>(l=e,y),withRetryInterval:(t,s)=>(e.isNonNullable(t)&&(f=t),e.isNonNullable(s)&&(S=s),y),withTimeout:e=>(d=e,y),withFinally:e=>(h=e,y),send:v,abort:()=>{n&&(n.abort(),n=void 0),c=!0,h&&h()}};return y}class ye{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<.1*this.currentRate?t=.8:e<.5*this.currentRate?t=.5:e<.7*this.currentRate&&(t=.3)),e=Math.max(1,Math.min(e,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end&&(this._doMergeIntervals(e,t),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let s=0,i=0;for(;this.intervals.length>0;){const e=this.intervals[0];if(e.end<=t)s+=e.end-e.start,i+=e.bytes,this.intervals.splice(0,1);else{if(e.start>=t)break;{const a=t-e.start,r=e.end-e.start;s+=a;const o=e.bytes*a/r;i+=o,e.start=t,e.bytes-=o}}}if(i>0&&s>0){const a=8*i/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>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 Te{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:'warn'}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=fe(),i=s=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=s,e._errorCB?e._errorCB(s):(this.limitCompleteCount(),this.completeRequests[t]=e)};e._request=ve(t,(i=>{e._complete=1,e._responseData=i,e._downloadTime=fe()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(i,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)}),(()=>i('error')),(()=>{e._retry=1,e._retryCB&&e._retryCB()})),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{e._finallyCB&&e._finallyCB()})),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(s>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),s),!1)}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(!e)return;this.activeRequests[e]||this.completeRequests[e]||(this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e))}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach((e=>{e&&e._request&&e._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,i){const a={};return a.send=()=>{const r=this.activeRequests[e]||this.completeRequests[e];if(r)r._cb=t,r._errorCB=s,r._retryCB=i,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(e),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${e}`);else{const t=this.pendingQueue.indexOf(e);-1!==t&&this.pendingQueue.splice(t,1),this.logger(`Request not prefetched, starting new request, url=${e}${-1===t?'':'; removed pending'}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=i,a.abort=function(){a.request&&a.request.abort()},a.withFinally=e=>(a._finallyCB=e,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}class Ee{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new ye(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ge(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e)return void this._switchToQuality(t)}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ge(e),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return 0!==s&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:'buffering',isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener('error',(s=>{this.destroyed||(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:'error',type:'media'}))})),e.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),e.pause(),this.videoPlayStarted=!1}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),e.addEventListener('playing',(()=>{t('playing')})),e.addEventListener('stalled',(()=>this._fixupStall())),e.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let i;0!==s&&(i=t.buffered.start(s-1),t.currentTime<i&&(e('Fixup stall'),t.currentTime=i))}_selectQuality(e){const{videoElement:t}=this.params;let s,i,a;const r=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let t=0;t<this.manifest.length;++t)a=this.manifest[t],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<e&&r>Math.min(a.video.height,a.video.width)?(!i||a.bitrate>i.bitrate)&&(i=a):(!s||s.bitrate>a.bitrate)&&(s=a));return i||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||e.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:i,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s('setting video src'),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())})),this.videoPlayStarted=!1,i.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(e,t,s){const i=(...a)=>{s.apply(null,a),e.removeEventListener(t,i)};e.addEventListener(t,i)}(i,'progress',(()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Te(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(e,(()=>this._switchToQuality(e)))}_representation(t){const{logger:s,videoElement:i,playerCallback:a}=this.params;let r=!1,o=null,n=null,d=null,u=null,h=!1;const c=()=>{const e=r&&(!h||h===this.rep);return e||s('Not running!'),e},l=(e,t,s)=>{d&&d.abort(),d=ve(this.urlResolver.resolve(e,!1),t,s,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{d=null})).send()},p=(t,s,i)=>{e.assertNonNullable(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),s,i,(()=>this._retryCallback())).withFinally((()=>{n=null})).send()},m=e=>{const t=i.playbackRate;i.playbackRate!==e&&(s(`Playback rate switch: ${t}=>${e}`),i.playbackRate=e)},S=e=>{this.lowLatency=e,s(`lowLatency changed to ${e}`),f()},f=()=>{if(this.lowLatency){let e=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const t=fe()-6e4;let i=0;for(let s=0;s<this.bufferStates.length;s++){const a=this.bufferStates[s];e=Math.min(e,a.buf),a.ts<t&&i++}this.bufferStates.splice(0,i),s(`update playback rate; minBuffer=${e} drop=${i} jitter=${this.sourceJitter}`);let a=e-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=t=>{let i;const r=()=>i&&i.start?i.start.length:0,o=e=>i.start[e]/1e3,n=e=>i.dur[e]/1e3,d=e=>i.fragIndex+e,h=(e,t)=>({chunkIdx:d(e),startTS:o(e),dur:n(e),discontinuity:t}),l=()=>{let e=0;if(i&&i.dur){let t=Math.max(this.sourceJitter,1);for(this.lowLatency||(t+=2),e=i.dur.length-1;e>=0&&(t-=i.dur[e]/1e3,!(t<=0));--e);}return h(e,!0)},p=(e,t,s)=>{u&&u.abort(),u=ve(this.urlResolver.resolve(e,!0,this.lowLatency),t,s,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(s,n)=>{p(t,(t=>{if(!c())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&S(d);let u=0;for(let e=0;e<i.dur.length;++e)u+=i.dur[e];u>0&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,s((t=>{const s=r();if(!(s<=0)){if(e.isNonNullable(t))for(let e=0;e<s;e++)if(o(e)>t)return h(e);return l()}})(n))}),(()=>this._handleNetworkError()))},nextChunk:e=>{const t=r(),a=e?e.chunkIdx+1:0,o=a-i.fragIndex;if(!(t<=0)){if(!e||o<0||o-t>10)return s(`Resync: offset=${o} bChunks=${t} chunk=`+JSON.stringify(e)),l();if(!(o>=t))return h(a-i.fragIndex,!1)}}}},g=()=>{r=!1,n&&n.abort(),d&&d.abort(),u&&u.abort(),e.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:s=>{const{videoElement:i,logger:a}=this.params;let n,d,h,m,S,v,y,T=b(t.jidxUrl),E=0;const k=()=>{S&&(clearTimeout(S),S=void 0);const e=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),t=E+e,s=fe(),i=Math.min(1e4,t-s);E=s;const a=()=>{u||c()&&T.seek((()=>{c()&&(E=fe(),$(),k())}))};i>0?S=window.setTimeout((()=>{this.paused?k():a()}),i):a()},$=()=>{let e;for(;e=T.nextChunk(m);)m=e,N(e);const s=T.nextChunk(h);if(s){if(h&&s.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?k():(g(),this._initPlayerWith(t)));x(s)}else k()},P=(e,t)=>{if(!c()||!this.sourceBuffer)return;let s,r,o;const n=s=>{window.setTimeout((()=>{c()&&P(e,t)}),s)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const d=fe(),u=i.currentTime;!this.paused&&i.buffered.length>1&&v===u&&d-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),v!==u&&(v=u,y=d);const h=this._getBufferSizeSec();if(h>30)a(`Buffered ${h} seconds; delaying appendBuffer`),n(2e3);else try{this.sourceBuffer.appendBuffer(e),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),f(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),t&&t()}catch(e){if('QuotaExceededError'!==e.name)throw e;a('QuotaExceededError; delaying appendBuffer'),o=this.sourceBuffer.buffered.length,0!==o&&(s=this.sourceBuffer.buffered.start(0),r=u,r-s>4&&this.sourceBuffer.remove(s,r-3)),n(1e3)}}},w=()=>{d&&n&&(a([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),P(d,(function(){d=null,$()})))},A=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),x=e=>{c()&&p(A(e),((t,s)=>{if(c()){if(s/=1e3,d=t,h=e,o=e.startTS,s){const t=Math.min(10,e.dur/s);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*t:t}w()}}),(()=>this._handleNetworkError()))},N=t=>{c()&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(t),!1)))},_=e=>{c()&&(t.cachedHeader=e,P(e,(()=>{n=!0,w()})))};r=!0,T.seek((t=>{c()&&(E=fe(),t?(m=t,!e.isNullable(s)||t.startTS>s?x(t):(h=t,$())):k())}),s),t.cachedHeader?_(t.cachedHeader):l(t.headerUrl,_,(()=>this._handleNetworkError()))},stop:g,getTimestampSec:()=>o},h}_switchToQuality(t){const{logger:s,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),e.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),s(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,e.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return e.isNonNullable(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=t=>{if(!this.autoQuality)return;let s,i,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&t<this.bitrate&&(i=this._getBufferSizeSec(),a=t/this.bitrate,i>10&&a>.8||i>15&&a>.5||i>20&&a>.3)?e(`Not switching: buffer=${Math.floor(i)}; bitrate=${this.bitrate}; newRate=${Math.floor(t)}`):(s=this._selectQuality(t),s?this._switchToQuality(s):e(`Could not find quality by bitrate ${t}`))},i=(()=>({updateChunk:(e,s)=>{const i=fe();if(this.chunkRateEstimator.addInterval(e,i,s)){const a=this.chunkRateEstimator.getBitRate();return t({name:'bandwidth',size:s,duration:i-e,speed:a}),!0}},get:()=>{const e=this.chunkRateEstimator.getBitRate();return e?.85*e:0}}))();let a,r=-1/0,o=!0;const n=()=>{let e=i.get();if(e&&a&&this.autoQuality){if(o&&e>a&&be(r)<3e4)return;s(e)}o=this.autoQuality};return{updateChunk:(e,t)=>{const s=i.updateChunk(e,t);return s&&n(),s},notifySwitch:e=>{const t=fe();e<a&&(r=t),a=e}}}_fetchManifest(e,t,s){this.manifestRequest=ve(this.urlResolver.resolve(e,!0),t,s,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(e){const{videoElement:t}=this.params;Se(t).then((t=>{t||e?.()}))}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params;this.manifest=(e=>{const t=[];return e?.length?(e.forEach(((e,s)=>{e.video&&i.canPlayType(e.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(e.codecs)&&(e.index=s,t.push(e))})),t.sort((function(e,t){return e.video&&t.video?t.video.height-e.video.height:t.bitrate-e.bitrate})),t):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:'manifest',manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(e,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))}),(()=>this._refetchManifest(e)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var ke;!function(e){e.STOPPED='stopped',e.MANIFEST_READY='manifest_ready',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ke||(ke={}));const $e=[ke.PAUSED,ke.PLAYING,ke.READY],Pe=[ke.PAUSED,ke.PLAYING,ke.READY];class we{subscription=new e.Subscription;video;videoState=new k(ke.STOPPED);dash;representations$=new e.ValueSubject([]);textTracksManager=new Y;maxSeekBackTime$=new e.ValueSubject(1/0);zeroTime$=new e.ValueSubject(void 0);liveOffset=new z;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const s=e=>{t.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:e})};e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>({transition:e,type:'start'})))),this.videoState.stateChangeEnded$.pipe(e.map((e=>({transition:e,type:'end'}))))).subscribe((({transition:e,type:t})=>{this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.video=Q(t.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Z(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ke.READY&&this.videoState.setState(ke.READY)}),s)).add(i.pause$.subscribe((()=>{this.videoState.setState(ke.PAUSED)}),s)).add(i.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===h.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(ke.PLAYING)}),s)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map((e=>-e/1e3))).subscribe(this.params.output.duration$)).add(e.combine({zeroTime:this.zeroTime$.pipe(e.filter(e.isNonNullable)),position:i.timeUpdate$}).subscribe((({zeroTime:e,position:t})=>this.params.output.liveTime$.next(e+1e3*t)),s)).add(H(this.video,this.params.desiredState.isLooped,s)).add(j(this.video,this.params.desiredState.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(this.params.output.volume$,s)).add(X(this.video).subscribe(this.params.output.firstBytesEvent$)).add(W(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:e}})=>{const t=e&&b[e].height;this.dash.setMaxAutoQuality(t)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case ke.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case ke.MANIFEST_READY:case ke.READY:break;case ke.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case ke.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return e.assertNever(t.to)}}),s)).add(e.merge(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekState.stateChangeEnded$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Ee({videoElement:this.video,config:{CHUNK_DURATION:this.params.config.chunkDuration,BUFFER_OPTIMAL_DURATION:this.params.config.optimalBufferDuration,MAX_PARALLEL_REQUESTS:this.params.config.maxParallelRequests},playerCallback:this._dashCb,logger:e=>{this.params.dependencies.logger.log({message:String(e),component:'LiveDashPlayer'})}});return e.pause(),e}prepare(){const t=this.representations$.getValue(),s=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&e.isNonNullable(s)?s:ne(t.map((({track:e})=>e)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.id,r=t.find((({track:e})=>e.id===a))?.representation;e.assertNonNullable(r,'Representations missing'),this.dash.startPlay(r,i),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(i)}setVideoTrack(t){const s=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;e.assertNonNullable(s,`No such representation ${t}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.dash.reinit(S(this.params.source.url,s))}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,s=[];for(const t of e){const e=t.name??t.index.toString(10),i=me(t.name)??T(t.video),a=t.bitrate/1e3,r={...t.video};if(!i)continue;const o={id:e,quality:i,bitrate:a,size:r};s.push({track:o,representation:t})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map((({track:e})=>e))),this.videoState.getTransition()?.to===ke.MANIFEST_READY&&this.videoState.setState(ke.MANIFEST_READY);break}case'qualitySwitch':{const s=t.quality,i=this.representations$.getValue().find((({representation:e})=>e===s))?.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),e.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:s}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,s);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==exports.PlaybackState.STOPPED){if(!s){if(Pe.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;e.isNonNullable(t)&&this.setVideoTrack(t);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if(a?.to!==exports.PlaybackState.PAUSED&&r.state===h.Requested&&$e.includes(t))this.seek(r.position-this.liveOffset.getTotalPausedTime());else switch(t){case ke.STOPPED:return this.videoState.startTransitionTo(ke.MANIFEST_READY),void this.dash.attachSource(S(this.params.source.url));case ke.MANIFEST_READY:this.videoState.startTransitionTo(ke.READY),this.prepare();break;case ke.READY:return void(i===exports.PlaybackState.PAUSED?this.videoState.setState(ke.PAUSED):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ke.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(ke.PAUSED)}))));case ke.PLAYING:return void(i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(ke.PAUSED),this.liveOffset.pause(),this.dash.pause()));case ke.PAUSED:return void(i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ke.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(ke.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return e.assertNever(t)}}}else t!==ke.STOPPED&&(this.videoState.startTransitionTo(ke.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(ke.STOPPED))}}var Ae=e=>{const t=e.get('X-Delivery-Type'),s=e.get('X-Reused');return{type:null===t?exports.HttpConnectionType.HTTP1:t??void 0,reused:null===s?void 0:{1:!0,0:!1}[s]??void 0}},xe=(e,t)=>{let s=0;for(let i=0;i<e.length;i++){const a=1e3*e.start(i),r=1e3*e.end(i);a<=t&&t<=r&&(s=r)}return Math.max(s-t,0)};class Ne{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,a,r){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(e.assertNonNullable(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((e=>e.split(':').map((e=>e.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(e){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(e)}`,e),e}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('XHR2Failover','XHR failed, retrying failover host');else{let e;this._failoverIndex>=this._failoverHosts.length?(e=this._url,this._failoverIndex=0):(e=this._url.replace((e=>{const t=document.createElement('a');return t.href=e,t.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',e,!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 _e{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(e){if('QuotaExceededError'!==e.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',e),e;{this._isFull=!0;const e=this._sourceBuffer.buffered;let t=0;for(let s=0,i=e.length;s<i;s++)t+=e.end(s)-e.start(s);t&&(this._maxBufferDuration=Math.round(t))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,a,r,o){this.abort((()=>{let n=0;const d=Date.now();let u=0,h=0,c=0;const l=e=>{i(_e._str2ua(e.substr(n))),n=e.length};let p=e.baseURL+'&bytes='+t+'-'+s;this._params.requestQuic&&(p=F(p)),this._lastXhr=new Ne(p,e.failoverHosts,(e=>{this._lastXhr=void 0,l(e);const t=Date.now()-d;this._params.onBandwidthChange({size:e.length,duration:t,speed:8*e.length/(t/1e3)}),this._onDashCallback('loading',{size:e.length,done:!0}),a?.()}),(e=>{if(e.length-n>o&&l(e),0===h)return void(h=Date.now());c=e.length-u;const t=Date.now()-h;c>=102400&&t>=1e3&&(this._params.onBandwidthChange({size:c,duration:t,speed:8*c/(t/1e3)}),c=0,u=e.length,h=Date.now()),this._onDashCallback('loading',{size:e.length,done:!1})}),r,((e,t,s)=>this._params.onError(e,t,s)))}))}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),e?.()}))}))}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(e){throw this._params.onError('SourceBuffer','Source Buffer update error',e),e}};return this._sourceBuffer.addEventListener('updateend',t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener('updateend',e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=_e._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class De{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=(e,t)=>{const s=e?parseFloat(e.replace(',','.')):NaN;return(isNaN(s)?0:s)*t},s=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(e),i='-'===s?.[1]?-1:1;t(s?.[2],i),t(s?.[3],i),t(s?.[4],i),t(s?.[5],i);return 3600*t(s?.[6],i)+60*t(s?.[7],i)+t(s?.[8],i)}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=F(s)),new Ne(s,t,(e=>{this.attachManifest(e,t,(e=>{const t=document.createElement('a');return t.href=e,t.origin})(s))}),void 0,(e=>{this._params.onResponseHeaders(e)}),((e,t,s)=>this._params.onError(e,t,s)))}attachManifest(e,t,s){const i=(new DOMParser).parseFromString(e,'text/xml').documentElement,a=(e,t)=>{const s=e.attributes.getNamedItem(t);return s?s.value:null};this._duration=this._parseDurationFromISO8601(String(a(i,'mediaPresentationDuration')));const r=[],o=[];Array.prototype.forEach.call(i.getElementsByTagName('Representation'),(e=>{const i=e.getElementsByTagName('SegmentBase')[0],n=i&&a(i,'indexRange').split('-'),d=i&&i.getElementsByTagName('Initialization')[0],u=d&&a(d,'range').split('-');if(!u||!n){const t=e.parentElement;if('text'===t?.getAttribute('contentType')){const i=e.getAttribute('id')??void 0,a=(s?s+'/':'')+e.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=t.getAttribute('lang')??void 0;a&&o.push({id:i,url:a,language:r})}return}const h=Number(e.attributes.getNamedItem('bandwidth')?.value),c=(s?s+'/':'')+e.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=e.attributes.getNamedItem('frameRate')?.value??void 0;l=p?ee(p):void 0,r.push({width:Number(e.attributes.getNamedItem('width')?.value),height:Number(e.attributes.getNamedItem('height')?.value),bandwidth:h,baseURL:c,failoverHosts:t,indexFrom:Number(n[0]),indexTo:Number(n[1]),initFrom:Number(u[0]),initTo:Number(u[1]),codecs:e.attributes.getNamedItem('codecs')?.value??void 0,mimeType:e.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*h/8,bufferLength:.1,name:e.attributes.getNamedItem('okQuality')?.value??void 0,id:e.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,o.forEach((({id:e,language:t,url:s})=>{const i=document.createElement('track');i.setAttribute('src',s),e&&i.setAttribute('id',e),t&&i.setAttribute('srclang',t),this._video.appendChild(i)})),this._representations.sort(((e,t)=>t.bandwidth-e.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(e,t){if(e===this._currentRepresentation)return void(t&&t());if(e.refs)return void this._stream.abort((()=>{this._stream.append(e.initMessage,t)}));const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,(s=>{let i=e.initTo-e.initFrom+1;if(!s.byteLength)return void this._params.onError('EmptyResponse','Empty response');e.initMessage=new Uint8Array(s.buffer,0,i);const a=new DataView(s.buffer);i+=12;const r=a.getUint32(i+4,!1);i+=8;let o=a.getUint32(i,!1),n=a.getUint32(i+4,!1)+(e.indexTo+1);i+=8;const d=a.getUint16(i+2,!1);i+=4,e.refs=[];for(let t=0;t<d;t+=1){const t=n+(2147483647&a.getUint32(i,!1)),s=o+a.getUint32(i+4,!1);i+=12,e.refs.push({fromTime:o/r,toTime:s/r,fromOffset:n,toOffset:t-1}),n=t,o=s}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)}),void 0,(e=>{this._params.onResponseHeaders(e),this._params.onIdxRequestPing(Date.now()-s)}),e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const s=new t;let i,a;const r=()=>{const t=this._findRef(this._video.currentTime);if(!t||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 e=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),e)}const s=this._appendVector[String(t.fromTime)];let r;s!==i&&(i=s,this._params.onRepresentationPlay(s));if(this._findRef(t.toTime)){const t=this._buffer.getByTime(this._video.currentTime);if(!t)return void this._onDashCallback('buffering');r=t.end-this._video.currentTime,r<e.bufferLength&&(this._onDashCallback('buffering'),a!==t.end&&(a=t.end,window.setTimeout((()=>{try{const e=this._buffer.getNextWithGap(t);e&&(this._video.currentTime=e.start)}catch(e){throw this._params.onError('GapSyncError',`Seek Error ${String(e)}`,e),e}}),1e3*r)))}},o=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(e){throw this._params.onError('LoopError',`Dash Loop exception ${String(e)}`,e),e}o()}),250)},n=()=>{if(!this._stream)try{const t=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new _e({mediaSource:s,sourceBuffer:t,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(e){throw this._params.onError('DashSourceOpen',`Source open exception ${String(e)}`,e),e}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener('sourceopen',n),s.removeEventListener('webkitsourceopen',n)};s.addEventListener('sourceopen',n,!1),s.addEventListener('webkitsourceopen',n,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener('waiting',(()=>{const e=this._video&&this._video.played.length;e&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(e-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(e,t,s=!1,i=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,(()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const e=this._findRef(this._video.currentTime),s=Math.abs(this._video.currentTime-t),r=i||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===e||s<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,((e,t)=>this._stream.append(e,t)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(e=>this._params.onResponseHeaders(e)),e.bufferSize)}}))}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i)return void(this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime));const a=.1;if(i.toTime<s.end+a){const t=this._findRef(i.toTime);t&&t.toTime<s.end+a?(this._buffer.smartRemove(i.fromTime-a,t.toTime+a,((e,t)=>this._stream.remove(e,t))),this._loadRef(e,t.toTime)):(this._buffer.smartRemove(i.fromTime-a,i.toTime+a,((e,t)=>this._stream.remove(e,t))),this._loadRef(e,i.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!e.isNullable(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&0===t.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let i=0;i<t.length;i++){const a=t[i];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const s=t[t.length-1];if(e>s.toTime)return s}return s}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const s=t[t.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),i=this._video.buffered.end(t);if(e>s&&e<i)return Math.round(10*i)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Re;!function(e){e.STOPPED='stopped',e.MANIFEST_LOADED='manifest-loaded',e.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',e.METADATA_LOADED='metadata-loaded',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Re||(Re={}));const Ie=[Re.PAUSED,Re.PLAYING];class Ce{videoState=new k(Re.STOPPED);subscription=new e.Subscription;video;buffer;dash;representations$=new e.ValueSubject([]);currentRepresentation$=new e.ValueSubject(void 0);params;textTracksManager=new Y;elementSize$=new e.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new e.Subject,responseHeaders$:new e.Subject,manifestReady$:new e.Subject,representationPlay$:new e.Subject,error$:new e.Subject};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),e.merge(this.videoState.stateChangeStarted$.pipe(e.map((e=>({transition:e,type:'start'})))),this.videoState.stateChangeEnded$.pipe(e.map((e=>({transition:e,type:'end'}))))).subscribe((({transition:e,type:t})=>{this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.video=Q(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new J(this.video),this.dash=new De({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:e=>this.dashLiteEvents.idxRequestPing$.next(e),onResponseHeaders:e=>this.dashLiteEvents.responseHeaders$.next(e),onManifestReady:e=>this.dashLiteEvents.manifestReady$.next(e),onRepresentationPlay:e=>this.dashLiteEvents.representationPlay$.next(e),onBandwidthChange:e=>this.params.dependencies.throughputEstimator.addRawSpeed(e.size,e.duration),onError:(e,t,s)=>{this.log({message:`[DashLite error], ${e}`}),this.dashLiteEvents.error$.next({id:e,message:t,thrown:s})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},a=()=>{const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.autoVideoTrackSwitching.getTransition();return t?t.to:e},r=Z(this.video),o=(e,t)=>this.subscription.add(e.subscribe(t,i));o(r.timeUpdate$,t.position$),o(r.durationChange$,t.duration$),o(r.ended$,t.endedEvent$),o(r.looped$,t.loopedEvent$),o(r.error$,t.error$),o(r.isBuffering$,t.isBuffering$),o(r.firstFrame$,t.firstFrameEvent$),this.subscription.add(r.seeking$.subscribe((()=>{e.isNullable(this.params.desiredState.seekState.getState().state!==h.Applying)&&(this.videoState.getState()===Re.PLAYING||this.videoState.getState()===Re.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(H(this.video,s.isLooped,i)),this.subscription.add(j(this.video,s.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,s,t),o(ue(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Re.READY&&this.videoState.setState(Re.READY)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Re.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Re.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),i)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Re.METADATA_LOADED)}),i)).add(r.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(e.map((({id:e,message:t,thrown:s})=>({id:`DashLite_${e}`,message:t,thrown:s})))).subscribe(this.params.output.error$)).add(e.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$,e.fromEvent(this.video,'progress')).pipe(e.map((()=>{const t=this.currentRepresentation$.getValue(),s=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),r=this.params.desiredState.videoTrack.getState(),o=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),n=this.elementSize$.getValue(),d=a();let u;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&e.isNonNullable(r))u=r;else{const e=xe(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);u=ne(s.map((({track:e})=>e)),{container:n,throughput:o,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:i,currentRepresentation:t})?.id}return e.isNonNullable(u)?s.find((({track:e})=>e.id===u))?.representation:void 0})),e.filterChanged()).subscribe(this.currentRepresentation$,i)).add(e.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(e.filter((e=>e.to===Re.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(e.filter(e.isNonNullable))}).pipe(e.once()).subscribe((()=>this.videoState.setState(Re.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(e.filter(e.isNonNullable),e.filterChanged(((e,t)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?e.height<=t.height:e===t))).subscribe((e=>{const t=xe(this.video.buffered,1e3*this.video.currentTime),s=Math.min(t/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||s<=.5||!a())&&(this.dash.setQualityByRepresentation(e,!0),this.params.output.hostname$.next(de(e.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((e=>{const{type:t,reused:s}=Ae(e);this.params.output.httpConnectionType$.next(t),this.params.output.httpConnectionReused$.next(s)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(e.once()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((e=>this.params.dependencies.throughputEstimator.addRawRtt(e)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(e.filter(e.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return e.assertNever(t)}}handleManifestReady=e=>{const t=[];for(const s of e){const e=s.name??s.id??s.height.toString(10),i=(s.name&&me(s.name))??T(s),a=s.bandwidth/1e3,r={width:s.width,height:s.height},o=s.fps;if(!i)continue;const n={id:e,quality:i,bitrate:a,size:r,fps:o};t.push({track:n,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map((({track:e})=>e))),this.videoState.setState(Re.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find((({representation:t})=>t===e))?.track;if(t){this.params.output.currentVideoTrack$.next(t);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return e.assertNonNullable(t,'Can\'t select representation. something went wrong'),t};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(Re.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==exports.PlaybackState.STOPPED){if(!s)switch(a?.to!==exports.PlaybackState.PAUSED&&r.state===h.Requested&&Ie.includes(t)&&this.seek(r.position,r.forcePrecise),t){case Re.STOPPED:return this.videoState.startTransitionTo(Re.MANIFEST_LOADED),void this.prepare();case Re.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Re.INITIAL_REPRESENTATION_SELECTED);case Re.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Re.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Re.METADATA_LOADED:return this.videoState.startTransitionTo(Re.READY),void this.dash.updateRefsForCurrentTime();case Re.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Re.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Re.PLAYING),this.playIfAllowed()));case Re.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Re.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Re.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Re.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==Re.STOPPED&&(this.videoState.startTransitionTo(Re.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(Re.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))}}var Le,Be,Oe,Ve;!function(e){e.VIDEO='video',e.AUDIO='audio',e.TEXT='text'}(Le||(Le={})),function(e){e.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',e.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(Be||(Be={})),function(e){e.NONE='none',e.DOWNLOADING='downloading',e.DOWNLOADED='downloaded',e.PARTIALLY_FED='partially_fed',e.FED='fed'}(Oe||(Oe={})),function(e){e.MP4='mp4',e.WEBM='webm'}(Ve||(Ve={}));class Me{bufferFull$=new e.Subject;error$=new e.Subject;buffer;queue=[];currentTask=null;constructor(e){this.buffer=e,this.buffer.addEventListener('updateend',this.onUpdateEnd)}async append(e,t){return(!t||!t.aborted)&&new Promise((s=>{const i={operation:'append',data:e,signal:t,callback:s};this.queue.push(i),this.pull()}))}async remove(e,t,s){return(!s||!s.aborted)&&new Promise((i=>{const a={operation:'remove',from:e,to:t,signal:s,callback:i};this.queue.unshift(a),this.pull()}))}destroy(){this.buffer.removeEventListener('updateend',this.onUpdateEnd)}onUpdateEnd=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:'BufferTaskQueue',message:'Buffer appending or removal failed',thrown:e})}};pull(){if(this.buffer.updating||this.currentTask)return;const e=this.queue.shift();if(e){if(e.signal?.aborted)return e.callback(!1),void this.pull();this.currentTask=e;try{this.execute(this.currentTask)}catch(e){this.currentTask.callback(!1),this.currentTask=null}}}execute(t){const{operation:s}=t;switch(s){case'append':try{this.buffer.appendBuffer(t.data)}catch(e){throw e instanceof DOMException&&'QuotaExceededError'===e.name&&this.bufferFull$.next(t.data.byteLength),e}break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;default:e.assertNever(s)}}}var Fe;!function(e){e[e.HEADER=0]='HEADER',e[e.PARAM=1]='PARAM'}(Fe||(Fe={}));class Ue{throughputEstimator;requestQuic;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);abortAllController=new I;subscription=new e.Subscription;constructor({throughputEstimator:e,requestQuic:t}){this.throughputEstimator=e,this.requestQuic=t}onHeadersReceived(e){const{type:t,reused:s}=Ae(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=e.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=F(t));const s=yield R(t,{signal:this.abortAllController.signal}).catch(qe);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetchRange=e.abortable(this.abortAllController.signal,async function*(t,s,i,{method:a=Fe.HEADER,onProgress:r,signal:o}={}){let n=t;const d=new Headers;switch(a){case Fe.HEADER:d.append('Range',`${s}-${i}`);break;case Fe.PARAM:{const e=new URL(n,location.href);e.searchParams.append('bytes',`${s}-${i}`),n=e.toString();break}default:e.assertNever(a)}this.requestQuic&&(n=F(n));let u=this.abortAllController.signal;if(o){const t=new I;this.subscription.add(e.merge(e.fromEvent(this.abortAllController.signal,'abort'),e.fromEvent(o,'abort')).subscribe((()=>{t.abort()}))),(this.abortAllController.signal.aborted||o.aborted)&&t.abort(),u=t.signal}const h=e.now(),c=yield R(n,{headers:d,signal:u}).catch(qe);if(this.throughputEstimator?.addRawRtt(e.now()-h),!c)return null;if(!c.ok||!c.body)return Promise.reject(new Error(`Fetch error ${c.status}: ${c.statusText}`));this.onHeadersReceived(c.headers);const[l,p]=c.body.tee(),m=l.getReader();this.throughputEstimator?.trackStream(p);const S=parseInt(c.headers.get('Content-Length')??'',10);let f=0;const b=new ArrayBuffer(S),g=new Uint8Array(b),v=new DataView(b);let y=!1;const T=e=>{y=!0,qe(e)},E=e.abortable(u,async function*({done:t,value:s}){0===f&&this.lastRequestFirstBytes$.next(e.now()-h),t?r?.(v,f):s&&(g.set(s,f),f+=s.byteLength,r?.(v,f),yield m?.read().then(E,T))}.bind(this));return yield m?.read().then(E,T),y?null:b}.bind(this));fetchRepresentation=e.abortable(this.abortAllController.signal,async function*(e,t,s=0){const{from:i,to:a}=e.initRange;let r,o,n=i,d=a,u=!1;e.indexRange&&(r=e.indexRange.from,o=e.indexRange.to,u=a+1===r,u&&(n=Math.min(r,i),d=Math.max(o,a))),n=Math.min(n,0),d+=s;const h=yield this.fetchRange(e.url,n,d,{method:Fe.PARAM});if(!h)return null;const c=new DataView(h,i-n,a-n+1);if(!t.validateData(c))throw new Error('Invalid media file');const l=t.parseInit(c);let p;if(u&&void 0!==r&&void 0!==o)p=new DataView(h,r-n,o-r+1);else{const s=t.getIndexRange(l);if(s){const t=yield this.fetchRange(e.url,s.from,s.to,{method:Fe.PARAM});if(!t)return null;p=new DataView(t)}}if(!p)throw new ReferenceError('No way to load representation index');const m=t.parseSegments(p,l);return{dataView:new DataView(h),segments:m}}.bind(this));destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const qe=e=>{if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e},He=new TextDecoder('ascii'),je=e=>{let t=0,s=e.getUint32(t);t+=4;const i=new DataView(e.buffer,e.byteOffset+t,4),a=He.decode(i);t+=4,0===s?s=1/0:1===s&&(t+=8,s=1/0);const r=Math.min(s,e.byteLength)-t;return{id:a,size:s,contents:new DataView(e.buffer,e.byteOffset+t,r)}},Ge={validateData:e=>'ftyp'===He.decode(new DataView(e.buffer,e.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:e=>{const t=je(e),s=[];let i=0;const a=()=>{const e=t.contents.getUint32(i);return i+=4,e};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),o=a(),n=a(),d=255&a();let u=o/r*1e3,h=e.byteOffset+e.byteLength+n;for(let e=0;e<d;e++){const e=a(),t=e>>>31,i=e<<1>>>1,o=a();if(a(),0!==t)throw new Error('Unsupported multilevel sidx');const n=o/r*1e3;s.push({status:Oe.NONE,time:{from:u,to:u+n},byte:{from:h,to:h+i-1}}),u+=n,h+=i}return s},parseFeedableSegmentChunk:e=>{let t=0,s=!1,i=!1;for(;t<=e.byteLength&&!s;){const a=new DataView(e.buffer,e.byteOffset+t);try{const s=je(a);if(i||='mdat'===s.id,!(t+s.size<=e.byteLength))break;t+=s.size}catch(e){s=!0}}return t>0&&t<=e.byteLength&&i?new DataView(e.buffer,e.byteOffset,t):null}};var Ye,Qe;!function(e){e[e.EBML=440786851]='EBML',e[e.EBMLVersion=17030]='EBMLVersion',e[e.EBMLReadVersion=17143]='EBMLReadVersion',e[e.EBMLMaxIDLength=17138]='EBMLMaxIDLength',e[e.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',e[e.DocType=17026]='DocType',e[e.DocTypeVersion=17031]='DocTypeVersion',e[e.DocTypeReadVersion=17029]='DocTypeReadVersion',e[e.Void=236]='Void',e[e.Segment=408125543]='Segment',e[e.SeekHead=290298740]='SeekHead',e[e.Seek=19899]='Seek',e[e.SeekID=21419]='SeekID',e[e.SeekPosition=21420]='SeekPosition',e[e.Info=357149030]='Info',e[e.TimestampScale=2807729]='TimestampScale',e[e.Duration=17545]='Duration',e[e.Tracks=374648427]='Tracks',e[e.Chapters=272869232]='Chapters',e[e.Cluster=524531317]='Cluster',e[e.Timestamp=231]='Timestamp',e[e.SilentTracks=22612]='SilentTracks',e[e.SilentTrackNumber=22743]='SilentTrackNumber',e[e.Position=167]='Position',e[e.PrevSize=171]='PrevSize',e[e.SimpleBlock=163]='SimpleBlock',e[e.BlockGroup=160]='BlockGroup',e[e.EncryptedBlock=175]='EncryptedBlock',e[e.Attachments=423732329]='Attachments',e[e.Tags=307544935]='Tags',e[e.Cues=475249515]='Cues',e[e.CuePoint=187]='CuePoint',e[e.CueTime=179]='CueTime',e[e.CueTrackPositions=183]='CueTrackPositions',e[e.CueTrack=247]='CueTrack',e[e.CueClusterPosition=241]='CueClusterPosition',e[e.CueRelativePosition=240]='CueRelativePosition',e[e.CueDuration=178]='CueDuration',e[e.CueBlockNumber=21368]='CueBlockNumber',e[e.CueCodecState=234]='CueCodecState',e[e.CueReference=219]='CueReference',e[e.CueRefTime=150]='CueRefTime'}(Ye||(Ye={})),function(e){e.SignedInteger='int',e.UnsignedInteger='uint',e.Float='float',e.String='string',e.UTF8='utf8',e.Date='date',e.Master='master',e.Binary='binary'}(Qe||(Qe={}));const ze={[Ye.EBML]:{type:Qe.Master},[Ye.EBMLVersion]:{type:Qe.UnsignedInteger},[Ye.EBMLReadVersion]:{type:Qe.UnsignedInteger},[Ye.EBMLMaxIDLength]:{type:Qe.UnsignedInteger},[Ye.EBMLMaxSizeLength]:{type:Qe.UnsignedInteger},[Ye.DocType]:{type:Qe.String},[Ye.DocTypeVersion]:{type:Qe.UnsignedInteger},[Ye.DocTypeReadVersion]:{type:Qe.UnsignedInteger},[Ye.Void]:{type:Qe.Binary},[Ye.Segment]:{type:Qe.Master},[Ye.SeekHead]:{type:Qe.Master},[Ye.Seek]:{type:Qe.Master},[Ye.SeekID]:{type:Qe.Binary},[Ye.SeekPosition]:{type:Qe.UnsignedInteger},[Ye.Info]:{type:Qe.Master},[Ye.TimestampScale]:{type:Qe.UnsignedInteger},[Ye.Duration]:{type:Qe.Float},[Ye.Tracks]:{type:Qe.Master},[Ye.Chapters]:{type:Qe.Master},[Ye.Cluster]:{type:Qe.Master},[Ye.Timestamp]:{type:Qe.UnsignedInteger},[Ye.SilentTracks]:{type:Qe.Master},[Ye.SilentTrackNumber]:{type:Qe.UnsignedInteger},[Ye.Position]:{type:Qe.UnsignedInteger},[Ye.PrevSize]:{type:Qe.UnsignedInteger},[Ye.SimpleBlock]:{type:Qe.Binary},[Ye.BlockGroup]:{type:Qe.Master},[Ye.EncryptedBlock]:{type:Qe.Binary},[Ye.Attachments]:{type:Qe.Master},[Ye.Tags]:{type:Qe.Master},[Ye.Cues]:{type:Qe.Master},[Ye.CuePoint]:{type:Qe.Master},[Ye.CueTime]:{type:Qe.UnsignedInteger},[Ye.CueTrackPositions]:{type:Qe.Master},[Ye.CueTrack]:{type:Qe.UnsignedInteger},[Ye.CueClusterPosition]:{type:Qe.UnsignedInteger},[Ye.CueRelativePosition]:{type:Qe.UnsignedInteger},[Ye.CueDuration]:{type:Qe.UnsignedInteger},[Ye.CueBlockNumber]:{type:Qe.UnsignedInteger},[Ye.CueCodecState]:{type:Qe.UnsignedInteger},[Ye.CueReference]:{type:Qe.Master},[Ye.CueRefTime]:{type:Qe.UnsignedInteger}},We=e=>{const t=e.getUint8(0);let s=0;128&t?s=1:64&t?s=2:32&t?s=3:16&t&&(s=4);const i=Je(e,s),a=i in ze,r=a?ze[i].type:Qe.Binary,o=e.getUint8(s);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 d=new DataView(e.buffer,e.byteOffset+s+1,n-1),u=((o&255>>n)<<8*(n-1))+Je(d),h=s+n;let c;return c=h+u>e.byteLength?new DataView(e.buffer,e.byteOffset+h):new DataView(e.buffer,e.byteOffset+h,u),{tag:a?i:'0x'+i.toString(16).toUpperCase(),type:r,tagHeaderSize:h,tagSize:h+u,value:c,valueSize:u}},Je=(e,t=e.byteLength)=>{switch(t){case 1:return e.getUint8(0);case 2:return e.getUint16(0);case 3:return e.getUint16(0)<<8|e.getUint8(2);case 4:return e.getUint32(0);case 5:return e.getUint32(0)<<8|e.getUint8(4);case 6:return e.getUint32(0)<<16|e.getUint16(4);case 7:return e.getUint32(0)<<32|e.getUint16(4)<<8|e.getUint8(6);case 8:return e.getUint32(0)<<32|e.getUint32(4)}return 0},Ke=(t,s)=>{switch(s){case Qe.SignedInteger:return t.getInt8(0);case Qe.UnsignedInteger:return Je(t);case Qe.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Qe.String:return new TextDecoder('ascii').decode(t);case Qe.UTF8:return new TextDecoder('utf-8').decode(t);case Qe.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Qe.Master:case Qe.Binary:return t;default:e.assertNever(s)}},Xe=(e,t)=>{let s=0;for(;s<e.byteLength;){const i=new DataView(e.buffer,e.byteOffset+s),a=We(i);if(!t(a))return;a.type===Qe.Master&&Xe(a.value,t),s=a.value.byteOffset-e.byteOffset+a.valueSize}},Ze=[Ye.Info,Ye.SeekHead,Ye.Tracks,Ye.Chapters,Ye.Cluster,Ye.Cues,Ye.Attachments,Ye.Tags],et=[Ye.Timestamp,Ye.SilentTracks,Ye.SilentTrackNumber,Ye.Position,Ye.PrevSize,Ye.SimpleBlock,Ye.BlockGroup,Ye.EncryptedBlock],tt={validateData:e=>{if(e.getUint32(0)!==Ye.EBML)return!1;let t,s,i;const a=We(e);return Xe(a.value,(({tag:e,type:a,value:r})=>(e===Ye.EBMLReadVersion?t=Ke(r,a):e===Ye.DocType?s=Ke(r,a):e===Ye.DocTypeReadVersion&&(i=Ke(r,a)),!0))),(void 0===t||t<=1)&&void 0!==s&&'webm'===s&&(void 0===i||i<=2)},parseInit:t=>{let s,i,a,r,o,n,d=!1,u=!1,h=!1;return Xe(t,(({tag:e,type:t,value:c,valueSize:l})=>{if(e===Ye.SeekID){const e=Ke(c,t);n=Je(e)}else e!==Ye.SeekPosition&&(n=void 0);return e===Ye.Segment?(s=c.byteOffset,i=c.byteOffset+l):e===Ye.Info?d=!0:e===Ye.SeekHead?u=!0:e===Ye.TimestampScale?a=Ke(c,t):e===Ye.Duration?r=Ke(c,t):e===Ye.SeekPosition&&n===Ye.Cues?o=Ke(c,t):d&&u&&Ze.includes(e)&&(h=!0),!h})),e.assertNonNullable(s,'Failed to parse webm Segment start'),e.assertNonNullable(i,'Failed to parse webm Segment end'),e.assertNonNullable(r,'Failed to parse webm Segment duration'),a=a??1e6,{segmentStart:Math.round(s/1e9*a*1e3),segmentEnd:Math.round(i/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:o}},getIndexRange:t=>{if(e.isNullable(t.cuesSeekPosition))return;const s=t.segmentStart+t.cuesSeekPosition;return{from:s,to:s+1048576}},parseSegments:(t,s)=>{let i=!1,a=!1;const r=t=>e.isNonNullable(t.time)&&e.isNonNullable(t.position),o=[];let n;return Xe(t,(({tag:e,type:t,value:s})=>{switch(e){case Ye.Cues:i=!0;break;case Ye.CuePoint:n&&r(n)&&o.push(n),n={};break;case Ye.CueTime:n&&(n.time=Ke(s,t));break;case Ye.CueTrackPositions:break;case Ye.CueClusterPosition:n&&(n.position=Ke(s,t));break;default:i&&Ze.includes(e)&&(a=!0)}return!(i&&a)})),n&&r(n)&&o.push(n),o.map(((e,t)=>{const{time:i,position:a}=e,r=o[t+1];return{status:Oe.NONE,time:{from:i,to:r?r.time:s.segmentDuration},byte:{from:s.segmentStart+a,to:r?s.segmentStart+r.position-1:s.segmentEnd-1}}}))},parseFeedableSegmentChunk:e=>{let t=0,s=!1;try{Xe(e,(i=>i.tag===Ye.Cluster?i.tagSize<=e.byteLength?(t=i.tagSize,!1):(t+=i.tagHeaderSize,!0):!!et.includes(i.tag)&&(t+i.tagSize<=e.byteLength&&(t+=i.tagSize,s||=[Ye.SimpleBlock,Ye.BlockGroup,Ye.EncryptedBlock].includes(i.tag)),!0)))}catch(e){}return t>0&&t<=e.byteLength&&s?new DataView(e.buffer,e.byteOffset,t):null}};class st{onLastSegment$=new e.ValueSubject(!1);fullyBuffered$=new e.ValueSubject(!1);playingRepresentation$=new e.ValueSubject(void 0);error$=new e.Subject;gaps=[];subscription=new e.Subscription;kind;container;containerParser;initData;representations;segments;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;segmentDownloadPromise;downloadAbortController=new I;destroyAbortController=new I;getCurrentPosition;loadAllInitsPromise;allInitsLoaded=!1;tuning;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;constructor(t,s,i,a,{fetcher:r,tuning:o,getCurrentPosition:n}){switch(this.fetcher=r,this.tuning=o,this.getCurrentPosition=n,this.container=i,i){case Ve.MP4:this.containerParser=Ge;break;case Ve.WEBM:this.containerParser=tt;break;default:e.assertNever(i)}this.initData=new Map,this.segments=new Map,this.representations=new Map(a.map((e=>[e.id,e]))),this.kind=t,this.mediaSource=s,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}startWith=e.abortable(this.destroyAbortController.signal,async function*(t){const s=this.representations.get(t);e.assertNonNullable(s,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${s.mime}; codecs="${s.codecs}"`),this.sourceBufferTaskQueue=new Me(this.sourceBuffer),this.subscription.add(e.fromEvent(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(e=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:e})))),this.subscription.add(e.fromEvent(this.sourceBuffer,'error').subscribe((e=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:e})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((e=>this.pruneBuffer(e)))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((e=>this.error$.next(e))));const i=yield this.fetcher.fetchRepresentation(s,this.containerParser).catch((e=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:e})));if(!i)return;const{dataView:a,segments:r}=i;let o=0;for(const e of r)e.time.from-o>=300&&this.gaps.push({representation:s.id,from:o,to:e.time.from}),o=e.time.to;e.isNonNullable(s.duration)&&s.duration-o>=300&&this.gaps.push({representation:s.id,from:o,to:s.duration});const n=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(t,n),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.segments.set(t,r)}.bind(this));switchTo=e.abortable(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=t,!this.initData.has(t))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const s=this.representations.get(t);e.assertNonNullable(s,`No such representation ${t}`);const i=yield this.fetcher.fetchRepresentation(s,this.containerParser,0).catch((e=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:e})));if(!i)return;const{dataView:a,segments:r}=i,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(t,o),this.segments.set(t,r)}const s=this.initData.get(t);e.assertNonNullable(s,`No init buffer for ${t}`),e.assertNonNullable(this.sourceBuffer,'SourceBuffer not inited yet'),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),e.isNonNullable(this.playingRepresentationId)&&this.segments.get(this.playingRepresentationId)?.forEach((e=>{e.status===Oe.FED?e.status=Oe.NONE:e.status===Oe.PARTIALLY_FED&&this.abortSegment(e)}));const i=this.getCurrentPosition();e.isNonNullable(i)&&this.maintain(i)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new I,this.abortBuffer()}maintain(t){if(e.isNullable(this.downloadingRepresentationId)||e.isNullable(this.playingRepresentationId)||e.isNullable(this.sourceBuffer)||this.onLastSegment$.getValue())return;const s=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);e.assertNonNullable(s,`No such representation ${this.downloadingRepresentationId}`),e.assertNonNullable(i,`No segments for ${this.downloadingRepresentationId}`);const a=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=xe(this.sourceBuffer.buffered,t);r=t+Math.min(e,this.tuning.representationSwitchForwardBufferGap)}let o=[];isFinite(this.bufferLimit)&&(e=>{let t=0;for(let s=0;s<e.length;s++)t+=e.end(s)-e.start(s);return 1e3*t})(this.sourceBuffer.buffered)>=.8*this.bufferLimit?this.pruneBuffer(1/0):(o=this.selectForwardBufferSegments(i,r),o.length&&this.loadSegments(o,s)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&a&&a.status===Oe.FED&&!o.length&&xe(this.sourceBuffer.buffered,t)>3e3&&this.loadAllInits().catch((e=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:e})));const n=i.at(-1);n&&n.status===Oe.FED&&(this.fullyBuffered$.next(!0),a===n&&this.onLastSegment$.next(!0))}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const s=this.segments.get(t);if(!s)return;return s.find((t=>t.time.from<=e&&t.time.to>=e))?.time.from??void 0}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t){const s=e.findIndex((({status:e,time:{from:s,to:i}})=>e===Oe.NONE&&(s>t||s<=t&&i>=t)&&i<=t+this.tuning.forwardBufferTarget));if(-1===s)return[];let i=0;const a=[];for(let t=s;t<e.length&&i<=this.tuning.segmentRequestSize;t++){const s=e[t];if(i+=s.byte.to+1-s.byte.from,s.status!==Oe.NONE)break;a.push(s)}return a}async loadSegments(t,s){if(!t.length)return;const i=t.at(0).byte.from,a=t.at(-1).byte.to;for(const e of t)e.status=Oe.DOWNLOADING,this.activeSegments.add({segment:e,loadedBytes:0,fedBytes:0});const{signal:r}=this.downloadAbortController;return this.segmentDownloadPromise=this.segmentDownloadPromise.then(e.abortable(this.destroyAbortController.signal,async function*(){if(r.aborted)for(const e of t)this.abortSegment(e);else yield this.fetcher.fetchRange(s.url,i,a,{method:Fe.PARAM,onProgress:(e,t)=>this.onSomeDataLoaded(e,s.id,i,t,r),signal:r})}.bind(this))).catch((e=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:e}))),this.segmentDownloadPromise}onSomeDataLoaded(e,t,s,i,a){if(!this.activeSegments.size)return;const r=e=>{this.abortSegment(e.segment)},o=e=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),e.segment.status=Oe.FED,this.activeSegments.delete(e),this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback((()=>{try{this.detectGaps(t,[e.segment])}catch(e){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:e})}this.gapDetectionIdleCallback=null})))};for(const t of this.activeSegments){const{segment:n}=t,d=n.byte.to-n.byte.from+1;if(a.aborted)return void r(t);const u=n.byte.from>=s,h=n.byte.from<s+i,c=n.byte.to<=s+i;if(n.status===Oe.DOWNLOADING&&u&&h&&c){n.status=Oe.DOWNLOADED,this.activeSegments.delete(t);const u=new DataView(e.buffer,e.byteOffset+n.byte.from-s,Math.min(d,s+i-n.byte.from));this.sourceBufferTaskQueue.append(u,a).then((e=>e&&!a.aborted?o(t):r(t)))}else if(this.tuning.enableSubSegmentBufferFeeding&&u&&h){const u=Math.min(d,i-(n.byte.from-s));t.buffer=t.buffer??new ArrayBuffer(d);const h=new DataView(t.buffer);for(let i=t.loadedBytes;i<u;i++)h.setUint8(i,e.getUint8(n.byte.from-s+i));t.loadedBytes=u;const c=new DataView(t.buffer,t.fedBytes,t.loadedBytes-t.fedBytes);if(d===t.loadedBytes&&t.fedBytes!==t.loadedBytes)n.status=Oe.DOWNLOADED,t.fedBytes=t.loadedBytes,this.sourceBufferTaskQueue.append(c,a).then((e=>e&&!a.aborted?o(t):r(t)));else if(t.loadedBytes>t.fedBytes){const e=this.containerParser.parseFeedableSegmentChunk(c);e&&(n.status=Oe.PARTIALLY_FED,t.fedBytes+=e.byteLength,this.sourceBufferTaskQueue.append(e,a).then((e=>{e&&!a.aborted||r(t)})))}}}}abortSegment(e){e.status===Oe.DOWNLOADING?e.status=Oe.NONE:e.status===Oe.PARTIALLY_FED&&this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then((()=>e.status=Oe.NONE));for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}async loadAllInits(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=Promise.all(Array.from(this.representations.entries()).map((([e,t])=>this.initData.has(e)?Promise.resolve():this.fetcher.fetchRepresentation(t,this.containerParser).then((t=>{if(!t)return;const{dataView:s,segments:i}=t,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(e,a),this.segments.set(e,i)}))))).then((()=>{this.allInitsLoaded=!0})).finally((()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}async pruneBuffer(t){const s=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||e.isNullable(s))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let a=0,r=1/0,o=-1/0,n=!1;for(const e of i){if(e.time.to>=s||a>=t)break;e.status===Oe.FED&&(r=Math.min(r,e.time.from),o=Math.max(o,e.time.to),a+=e.byte.to-e.byte.from)}if(n=isFinite(r)&&isFinite(o)&&(a>=t||t===1/0),!n){a=0,r=1/0,o=-1/0;for(const e of i)e.status===Oe.FED&&e.time.from>s+this.tuning.forwardBufferTarget&&(r=Math.min(r,e.time.from),o=Math.max(o,e.time.to),a+=e.byte.to-e.byte.from)}return n=isFinite(r)&&isFinite(o)&&(a>=t||t===1/0),!!n&&(await this.sourceBufferTaskQueue.remove(r,o/1e3),!0)}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(e){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:e})}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let t={representation:e,from:s.time.from,to:s.time.to};for(let e=0;e<this.sourceBuffer.buffered.length;e++){const i=1e3*this.sourceBuffer.buffered.start(e),a=1e3*this.sourceBuffer.buffered.end(e);if(!(a<=s.time.from||i>=s.time.to)){if(i<=s.time.from&&a>=s.time.to){t=void 0;break}a>s.time.from&&a<s.time.to&&(t.from=a),i<s.time.to&&i>s.time.from&&(t.to=i)}}t&&t.to-t.from>=1&&this.gaps.push(t)}}checkEjectedSegments(){if(e.isNullable(this.sourceBuffer)||e.isNullable(this.playingRepresentationId))return;const t=this.segments.get(this.playingRepresentationId);if(e.isNullable(t))return;const s=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const t=1e3*this.sourceBuffer.buffered.start(e),i=1e3*this.sourceBuffer.buffered.end(e);s.push({from:t,to:i})}const i=this.tuning.segmentTimelineTolerance;for(const e of t){const t=s.some((t=>t.from-i<=e.time.from&&t.to+i>=e.time.to));e.status!==Oe.FED||t||(e.status=Oe.NONE)}}}const it=e=>{if(!e.startsWith('P'))return;const t=(e,t)=>{const s=e?parseFloat(e.replace(',','.')):NaN;return(isNaN(s)?0:s)*t},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(e),i='-'===s?.[1]?-1:1;return 24*t(s?.[5],i)*60*600*1e3+60*t(s?.[6],i)*600*1e3+60*t(s?.[7],i)*1e3+1e3*t(s?.[8],i)},at=['timeupdate','progress','play','seeked','stalled'];var rt,ot;!function(e){e.NONE='none',e.MANIFEST_LOADED='manifest_loaded',e.REPRESENTATION_SELECTED='representation_selected'}(rt||(rt={}));class nt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;throughputEstimator;subscription=new e.Subscription;fetcher;state$=new k(rt.NONE);currentVideoRepresentation$=new e.ValueSubject(void 0);error$=new e.Subject;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);forceEnded$=new e.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new I;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ue({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=e.abortable(this.destroyController.signal,async function*(t,s){this.element=t,this.state$.startTransitionTo(rt.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(s);if(!i)return null;let a;try{a=((t,s)=>{const i={video:[],audio:[],text:[]},a=(new DOMParser).parseFromString(t,'application/xml').children[0],r=a.getElementsByTagName('Period')[0],o=r.children;let n;const d=a.getAttribute('mediaPresentationDuration'),u=r.getAttribute('duration');if(d)n=it(d);else if(u){const t=it(u);e.isNonNullable(t)&&(n=t)}let h=0;const c=a.getAttribute('profiles')?.split(',')??[],l=c.includes(Be.WEBM_AS_IN_FFMPEG)||c.includes(Be.WEBM_AS_IN_SPEC)?Ve.WEBM:Ve.MP4;for(const e of o){const t=e.getAttribute('mimeType'),a=e.getAttribute('codecs'),r=e.getAttribute('contentType')??t?.split('/')[0],o=e.getAttribute('profiles')?.split(',')??[],d=e.querySelectorAll('Representation');for(const u of d){const d=u.getAttribute('mimeType')??t,l=u.getAttribute('codecs')??a??'',p=u.getAttribute('contentType')??d?.split('/')[0]??r,m=e.getAttribute('profiles')?.split(',')??[],S=parseInt(u.getAttribute('width')??'',10),f=parseInt(u.getAttribute('height')??'',10),b=parseInt(u.getAttribute('bandwidth')??'',10)/1e3,g=u.getAttribute('frameRate')??'',v=u.getAttribute('quality')??void 0,y=g?ee(g):void 0,T=`${u.getAttribute('id')??(h++).toString(10)}@${'video'===p?`${f}p`:'audio'===p?`${b}Kbps`:l}`,E=u.querySelector('BaseURL')?.textContent?.trim()??'',k=new URL(E,s).toString(),$=[...c,...o,...m],P=u.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[w,A]=P.split('-').map((e=>parseInt(e,10))),x={from:w,to:A},N=u.querySelector('SegmentBase')?.getAttribute('indexRange'),[_,D]=N?N.split('-').map((e=>parseInt(e,10))):[],R=N?{from:_,to:D}:void 0;if(!p||!d)continue;const I={video:Le.VIDEO,audio:Le.AUDIO,text:Le.TEXT}[p];I&&i[I].push({id:T,kind:I,duration:n,profiles:$,initRange:x,indexRange:R,bitrate:b,mime:d,codecs:l,width:S,height:f,fps:y,quality:v,url:k})}}return{container:l,representations:i}})(i??'',s)}catch(e){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:e})}if(!a)return null;const r=({mime:e,codecs:s})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${s}"`));return this.manifest={...a,representations:Object.fromEntries(Object.entries(a.representations).map((([e,t])=>[e,t.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(rt.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this));initRepresentations=e.abortable(this.destroyController.signal,async function*(t,s){e.assertNonNullable(this.manifest),e.assertNonNullable(this.element),this.state$.startTransitionTo(rt.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning.dash,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new st(Le.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new st(Le.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),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$)),this.subscription.add(e.merge(this.forceEnded$,e.merge(this.videoBufferManager.onLastSegment$,this.audioBufferManager.onLastSegment$,this.videoBufferManager.fullyBuffered$,this.audioBufferManager.fullyBuffered$).pipe(e.filter((()=>!(!this.videoBufferManager||!this.audioBufferManager)&&[this.videoBufferManager.fullyBuffered$.getValue(),this.audioBufferManager.fullyBuffered$.getValue()].every((e=>e))&&[this.videoBufferManager.onLastSegment$.getValue(),this.audioBufferManager.onLastSegment$.getValue()].some((e=>e)))))).subscribe((()=>{if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((e=>!e.updating)))try{this.source?.endOfStream()}catch(e){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:e})}}))),this.subscription.add(e.merge(this.videoBufferManager.error$,this.audioBufferManager.error$).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((e=>this.source?.addEventListener('sourceopen',e)))),yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]),this.state$.setState(rt.REPRESENTATION_SELECTED),e.assertNonNullable(this.element),this.subscription.add(e.merge(...at.map((t=>e.fromEvent(this.element,t))),e.fromEvent(window,'online')).subscribe(this.tick,(e=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:e})}))),this.subscription.add(e.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(e.fromEvent(this.element,'waiting').subscribe((()=>{if(this.element&&2===this.element.readyState&&!this.element.seeking)for(let e=0;e<this.element.buffered.length;e++){if(this.element.buffered.start(e)<=this.element.currentTime&&this.element.buffered.end(e)>this.element.currentTime){this.element.currentTime=this.element.currentTime;break}}}))),this.tick()}.bind(this));async switchRepresentation(t,s){const i={[Le.VIDEO]:this.videoBufferManager,[Le.AUDIO]:this.audioBufferManager,[Le.TEXT]:null}[t];return e.assertNonNullable(i),i.switchTo(s)}seek(t,s){let i;e.assertNonNullable(this.element),e.assertNonNullable(this.videoBufferManager),e.assertNonNullable(this.audioBufferManager),this.videoBufferManager.abort(),this.audioBufferManager.abort(),i=s||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(this.videoBufferManager.findSegmentStartTime(t)??t,this.audioBufferManager.findSegmentStartTime(t)??t),this.videoBufferManager.maintain(i),this.audioBufferManager.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.state$.setState(rt.NONE)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=e.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(e=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:e})})),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const e=1e3*this.element.currentTime,t=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const s of[this.videoBufferManager,this.audioBufferManager])for(const i of s.gaps)if(s.playingRepresentation$.getValue()===i.representation&&i.from-t<=e&&i.to+t>e){if(1e3*this.element.duration-i.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=i.to/1e3;break}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(ot||(ot={}));const dt=({id:e,width:t,height:s,bitrate:i,fps:a,quality:r})=>{const o=(r?me(r):void 0)??T({width:t,height:s});return o&&{id:e,quality:o,bitrate:i,size:{width:t,height:s},fps:a}},ut=(e,t,s)=>{const i=Array.from(t).sort(((e,t)=>t.bitrate-e.bitrate)).indexOf(s);return e.at(Math.round(e.length*i/t.length))??e.at(-1)};class ht{subscription=new e.Subscription;videoState=new k(ot.STOPPED);video;player;params;elementSize$=new e.ValueSubject(void 0);textTracksManager=new Y;videoTracks=[];audioRepresentations;constructor(e){this.params=e,this.video=Q(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new nt({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=Z(this.video),a=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},r=(e,t)=>this.subscription.add(e.subscribe(t,a));r(i.timeUpdate$,t.position$),r(i.durationChange$,t.duration$),r(i.ended$,t.endedEvent$),r(i.looped$,t.loopedEvent$),r(i.error$,t.error$),r(i.isBuffering$,t.isBuffering$),r(i.currentBuffer$,t.currentBuffer$),r(i.firstFrame$,t.firstFrameEvent$),r(this.player.error$,t.error$),r(this.player.lastConnectionType$,t.httpConnectionType$),r(this.player.lastConnectionReused$,t.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(e.filter(e.isNonNullable),e.once()),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(H(this.video,s.isLooped,a)),this.subscription.add(j(this.video,s.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),r(ue(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(ot.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(ot.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===ot.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(e.filter((({to:e})=>e===rt.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(ot.READY)}))),this.subscription.add(e.merge(this.player.state$.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,s.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,e.fromEvent(this.video,'progress')).subscribe((()=>{const t=this.player.state$.getState(),i=this.player.state$.getTransition();if(t===rt.NONE||!this.videoTracks.length)return;const a=t===rt.MANIFEST_LOADED&&!i,r=s.autoVideoTrackSwitching.getState(),o=s.videoTrack.getState(),n=this.videoTracks.find((({track:{id:e}})=>e===o))?.track;s.autoVideoTrackSwitching.getTransition()&&s.autoVideoTrackSwitching.setState(r);const d=xe(this.video.buffered,1e3*this.video.currentTime),u=Math.min(d/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),h=ne(this.videoTracks.map((({track:e})=>e)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:s.autoVideoTrackLimits.getState(),forwardBufferHealth:u}),c=r?h??n:n??h;if(a){const t=c&&this.videoTracks.find((({track:e})=>e===c))?.representation;e.assertNonNullable(t);const s=ut(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),t);e.assertNonNullable(s),this.player.initRepresentations(t.id,s.id)}else{const e=c&&this.videoTracks.find((({track:e})=>e===c))?.representation;if(e){const t=ut(this.audioRepresentations,this.videoTracks.map((({representation:e})=>e)),e);this.player.switchRepresentation(Le.VIDEO,e.id),t&&this.player.switchRepresentation(Le.AUDIO,t.id)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(e.filterChanged(),e.map((e=>e&&this.videoTracks.find((({representation:{id:t}})=>t===e))?.track))).subscribe(t.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,s,t);const o=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,a))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(e){this.videoTracks=[];for(const t of e.representations.video){const e=dt(t);e&&this.videoTracks.push({track:e,representation:t})}this.audioRepresentations=Array.from(e.representations.audio).sort(((e,t)=>t.bitrate-e.bitrate)),this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:e})=>e)))}}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(a.state===h.Requested&&i?.to!==exports.PlaybackState.PAUSED&&t!==ot.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),s!==exports.PlaybackState.STOPPED){if(t===ot.STOPPED)return this.videoState.startTransitionTo(ot.READY),void this.prepare();switch(t){case ot.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(ot.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ot.PLAYING),this.playIfAllowed()));case ot.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ot.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case ot.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ot.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==ot.STOPPED&&(this.videoState.startTransitionTo(ot.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(ot.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(ot.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const ct={};var lt;!function(e){e.INITIALIZING='initializing',e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(lt||(lt={}));const pt=(t,s)=>new e.Observable((e=>{const i=(t,s)=>e.next(s);return t.on(s,i),()=>t.off(s,i)}));class mt{subscription=new e.Subscription;videoState=new k(lt.INITIALIZING);video;params;hls;textTracksManager=new Y;trackLevels=new Map;constructor(e){this.video=Q(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=t=>{e||this.params.output.error$.next({id:'timeout'===t?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:t}),e=!0},i=window.setTimeout((()=>t('timeout')),5e3);Promise.resolve().then((function(){return s(require('hls.js'))})).then((t=>{e||(ct.Hls=t.default,ct.Events=t.default.Events,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(ct.Hls,'hls.js not loaded'),this.hls=new ct.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(lt.STOPPED)}subscribe(){e.assertNonNullable(ct.Events,'hls.js not loaded');const{desiredState:t,output:s}=this.params,i=e=>{s.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,s.position$),r(a.durationChange$,s.duration$),r(a.ended$,s.endedEvent$),r(a.looped$,s.loopedEvent$),r(a.error$,s.error$),r(a.isBuffering$,s.isBuffering$),r(a.currentBuffer$,s.currentBuffer$),r(a.firstBytes$,s.firstBytesEvent$),r(a.firstFrame$,s.firstFrameEvent$),r(a.seeked$,s.seekedEvent$),this.subscription.add(H(this.video,t.isLooped,i)),this.subscription.add(j(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.hls,ct.Events.ERROR).subscribe((e=>{e.fatal&&s.error$.next({id:['HlsJsFatal',e.type,e.details].join('_'),message:`HlsJs fatal ${e.type} ${e.details}, ${e.err?.message} ${e.reason}`,thrown:e.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(lt.PLAYING),f(t.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(lt.PAUSED),f(t.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===lt.READY&&this.videoState.setState(lt.READY),this.videoState.getState()===lt.PLAYING&&this.playIfAllowed()}),i)),r(pt(this.hls,ct.Events.MANIFEST_PARSED).pipe(e.map((({levels:e})=>e.reduce(((e,t)=>{const s=t.name||t.height.toString(10),{width:i,height:a}=t,r=me(t.attrs.QUALITY??'')??T({width:i,height:a});if(!r)return e;const o=t.attrs['FRAME-RATE']?parseFloat(t.attrs['FRAME-RATE']):void 0,n={id:s.toString(),quality:r,bitrate:t.bitrate/1e3,size:{width:i,height:a},fps:o};return this.trackLevels.set(s,{track:n,level:t}),e.push(n),e}),[])))),s.availableVideoTracks$),r(pt(this.hls,ct.Events.LEVEL_LOADING).pipe(e.map((({url:e})=>de(e)))),s.hostname$),this.subscription.add(q(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(e=>{this.hls.nextLevel=e?-1:this.hls.currentLevel,this.hls.loadLevel=e?-1:this.hls.loadLevel}),{onError:i}));const o=e=>Array.from(this.trackLevels.values()).find((({level:t})=>t===e))?.track,n=pt(this.hls,ct.Events.LEVEL_SWITCHED).pipe(e.map((({level:e})=>o(this.hls.levels[e]))));n.pipe(e.filter(e.isNonNullable)).subscribe(s.currentVideoTrack$,i),this.subscription.add(q(t.videoTrack,(()=>o(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(e.isNullable(t))return;const s=this.trackLevels.get(t)?.level;if(!s)return;const i=this.hls.levels.indexOf(s),a=this.hls.currentLevel,r=this.hls.levels[a];!r||s.bitrate>r.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:n.pipe(e.map((e=>e?.id))),onError:i})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,s);const d=e.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==lt.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===h.Requested&&this.seek(a.position),s){case exports.PlaybackState.STOPPED:switch(t){case lt.STOPPED:break;case lt.READY:case lt.PLAYING:case lt.PAUSED:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case lt.PLAYING:break;case lt.STOPPED:this.prepare();break;case lt.READY:case lt.PAUSED:this.playIfAllowed();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case lt.PAUSED:break;case lt.STOPPED:this.prepare();break;case lt.READY:this.videoState.setState(lt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case lt.PLAYING:this.pause();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};prepare(){this.videoState.startTransitionTo(lt.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(lt.PLAYING);await Se(this.video)||(this.videoState.setState(lt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(lt.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(lt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const St=e=>{let t=null;if(e.QUALITY&&(t=me(e.QUALITY)),!t&&e.RESOLUTION){const[s,i]=e.RESOLUTION.split('x').map((e=>parseInt(e,10)));t=T({width:s,height:i})}return t??null},ft=async(e,t=e)=>{const s=await R(e),i=(await s.text()).split('\n'),a=[];for(let e=0;e<i.length;e++){const s=i[e].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const r=Object.fromEntries(s[1].split(',').map((e=>e.split('=')))),o=r.QUALITY??`stream-${r.BANDWIDTH}`,n=St(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const u=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let h;if(r.RESOLUTION){const[e,t]=r.RESOLUTION.split('x').map((e=>parseInt(e,10)));e&&t&&(h={width:e,height:t})}const c=new URL(i[++e],t).toString();n&&a.push({id:o,quality:n,url:c,bandwidth:d,size:h,fps:u})}return a};var bt,gt,vt;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(bt||(bt={}));class yt{subscription=new e.Subscription;videoState=new k(bt.STOPPED);video;params;textTracksManager=new Y;manifests$=new e.ValueSubject([]);maxSeekBackTime$;liveOffset=new z;manifestStartTime$=new e.ValueSubject(void 0);constructor(t){this.params=t,this.video=Q(t.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]),ft(S(this.params.source.url),this.params.source.url).then((e=>{this.manifests$.next([s,...e])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:e}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.maxSeekBackTime$=new e.ValueSubject(t.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??'master',r=this.manifests$.getValue();if(!r)return;const o=s?'master':a;return s&&!i&&t.startTransitionTo('master'),r.find((e=>e.id===o))}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.ended$,t.endedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),this.subscription.add(s.isLooped.stateChangeStarted$.subscribe((()=>s.isLooped.setState(!1)),i)),this.subscription.add(j(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(bt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(bt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===bt.READY&&this.videoState.setState(bt.READY),this.videoState.getState()===bt.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(e.filterChanged(),e.map((e=>-e/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&e.isNonNullable(i.to)){const e=i.to;this.params.desiredState.videoTrack.setState(e);const t=this.manifests$.getValue().find((t=>t.id===e));t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(de(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===bt.CHANGING_MANIFEST&&this.videoState.setState(s.to),t&&t.state===h.Requested&&this.seek(t.position)}),i)),this.subscription.add(a.loadedData$.subscribe((()=>{const e=this.video?.getStartDate()?.getTime();this.manifestStartTime$.next(e||void 0)}),i)),this.subscription.add(e.combine({startTime:this.manifestStartTime$.pipe(e.filter(e.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:e,currentTime:t})=>this.params.output.liveTime$.next(e+1e3*t)),i)),this.subscription.add(this.manifests$.pipe(e.map((e=>e.map((({id:e,quality:t,size:s,bandwidth:i,fps:a})=>({id:e,quality:t,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.stateChangeStarted$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(e.isNullable(t))return;const s=S(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',s),this.video.load(),(async e=>{const t=await R(e,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0})(s).then((t=>{e.isNullable(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(bt.PAUSED),this.liveOffset.pause(),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==bt.STOPPED&&(this.videoState.startTransitionTo(bt.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(bt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===bt.STOPPED)return this.videoState.startTransitionTo(bt.READY),void this.prepare();if(a||r){const e=this.videoState.getState();return this.videoState.setState(bt.CHANGING_MANIFEST),this.videoState.startTransitionTo(e),this.prepare(),void(o.state===h.None&&this.params.desiredState.seekState.setState({state:h.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if(i?.to!==exports.PlaybackState.PAUSED&&o.state===h.Requested)return this.videoState.startTransitionTo(bt.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case bt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(bt.PAUSED),this.liveOffset.pause(),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(bt.PLAYING),this.playIfAllowed()));case bt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(bt.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case bt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(bt.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):i?.to===exports.PlaybackState.PAUSED&&(f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case bt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(gt||(gt={}));class Tt{subscription=new e.Subscription;videoState=new k(gt.STOPPED);video;params;textTracksManager=new Y;manifests$=new e.ValueSubject([]);constructor(e){this.params=e,this.video=Q(e.container),this.params.output.element$.next(this.video);const t={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),ft(this.params.source.url).then((e=>{this.manifests$.next([t,...e])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:e}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??'master',r=this.manifests$.getValue();if(!r)return;const o=s?'master':a;return s&&!i&&t.startTransitionTo('master'),r.find((e=>e.id===o))}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(H(this.video,s.isLooped,i)),this.subscription.add(j(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(gt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(gt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===gt.READY&&this.videoState.setState(gt.READY),this.videoState.getState()===gt.PLAYING&&this.playIfAllowed()}),i).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),s=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&e.isNonNullable(i.to)){const e=i.to;this.params.desiredState.videoTrack.setState(e);const t=this.manifests$.getValue().find((t=>t.id===e));t&&(this.params.output.currentVideoTrack$.next(t),this.params.output.hostname$.next(de(t.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),s&&s.from===gt.CHANGING_MANIFEST&&this.videoState.setState(s.to),t.state===h.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(e.map((e=>e.map((({id:e,quality:t,size:s,bandwidth:i,fps:a})=>({id:e,quality:t,size:s,fps:a,bitrate:i})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=e.merge(s.playbackState.stateChangeStarted$,s.seekState.stateChangeEnded$,s.videoTrack.stateChangeStarted$,s.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();e.isNullable(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(gt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==gt.STOPPED&&(this.videoState.startTransitionTo(gt.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(gt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===gt.STOPPED)return this.videoState.startTransitionTo(gt.READY),void this.prepare();if(a||r){const e=this.videoState.getState();this.videoState.setState(gt.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const{currentTime:t}=this.video;return this.prepare(),void(o.state===h.None&&this.params.desiredState.seekState.setState({state:h.Requested,position:1e3*t,forcePrecise:!0}))}switch(i?.to!==exports.PlaybackState.PAUSED&&o.state===h.Requested&&this.seek(o.position),t){case gt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(gt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(gt.PLAYING),this.playIfAllowed()));case gt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(gt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case gt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(gt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case gt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(vt||(vt={}));class Et{subscription=new e.Subscription;videoState=new k(vt.STOPPED);video;trackUrls={};params;textTracksManager=new Y;constructor(e){this.params=e,this.video=Q(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([e,t],s)=>{const i=s.toString(10);this.trackUrls[i]={track:{quality:e,id:i},url:t}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:e})=>e))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},a=Z(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,t.position$),r(a.durationChange$,t.duration$),r(a.ended$,t.endedEvent$),r(a.looped$,t.loopedEvent$),r(a.error$,t.error$),r(a.isBuffering$,t.isBuffering$),r(a.currentBuffer$,t.currentBuffer$),r(a.firstBytes$,t.firstBytesEvent$),r(a.firstFrame$,t.firstFrameEvent$),r(a.seeked$,t.seekedEvent$),this.subscription.add(H(this.video,s.isLooped,i)),this.subscription.add(j(this.video,s.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(vt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(vt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===vt.READY&&this.videoState.setState(vt.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&e.isNonNullable(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===vt.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(s.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>s.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,s,t);const o=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();e.assertNonNullable(t,'MpegProvider: track is not selected');let{url:s}=this.trackUrls[t];e.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=F(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(de(s))}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(vt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED)return void(t!==vt.STOPPED&&(this.videoState.startTransitionTo(vt.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(vt.STOPPED),f(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(t===vt.STOPPED)return this.videoState.startTransitionTo(vt.READY),void this.prepare();if(a){const{currentTime:e}=this.video;return this.prepare(),void(r.state===h.None&&this.params.desiredState.seekState.setState({state:h.Requested,position:1e3*e,forcePrecise:!0}))}switch(i?.to!==exports.PlaybackState.PAUSED&&r.state===h.Requested&&this.seek(r.position),t){case vt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(vt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(vt.PLAYING),this.playIfAllowed()));case vt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(vt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case vt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(vt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}class kt{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const $t=(()=>{const{userAgent:e}=window.navigator;return!/chrome/i.test(e)&&/webkit|safari|khtml/i.test(e)})(),Pt=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),wt=document.createElement('video'),At={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(wt.canPlayType?.('application/x-mpegurl')||wt.canPlayType?.('vnd.apple.mpegURL'))},xt={mp4:Boolean(wt.canPlayType?.('video/mp4')),webm:Boolean(wt.canPlayType?.('video/webm'))},Nt={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},_t=(Nt.h264||Nt.h265)&&Nt.aac,Dt=!$t,Rt=Pt||$t,It=!At.hls||!Rt;const Ct=3e4,Lt=18e4,Bt=3,Ot=100,Vt={cacheDuration:12e4},Mt={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},Ft={maxPausedTime:3e4},Ut={maxPausedTime:3e4};class qt{current$=new e.ValueSubject({type:void 0});providerError$=new e.Subject;noAvailableProvidersError$=new e.Subject;providerOutput={position$:new e.ValueSubject(0),duration$:new e.ValueSubject(1/0),volume$:new e.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new e.ValueSubject(void 0),availableVideoTracks$:new e.ValueSubject([]),autoVideoTrackLimitingAvailable$:new e.ValueSubject(!1),currentBuffer$:new e.ValueSubject(void 0),isBuffering$:new e.ValueSubject(!0),error$:new e.Subject,willSeekEvent$:new e.Subject,seekedEvent$:new e.Subject,loopedEvent$:new e.Subject,endedEvent$:new e.Subject,firstBytesEvent$:new e.Subject,firstFrameEvent$:new e.Subject,isLive$:new e.ValueSubject(void 0),liveTime$:new e.ValueSubject(void 0),availableTextTracks$:new e.ValueSubject([]),currentTextTrack$:new e.ValueSubject(void 0),hostname$:new e.ValueSubject(void 0),httpConnectionType$:new e.ValueSubject(void 0),httpConnectionReused$:new e.ValueSubject(void 0),element$:new e.ValueSubject(void 0)};subscription=new e.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:s}=this.params.tuning,i=s.length?[...t.screenFormatsPriority.filter((e=>!s.includes(e))),...t.screenFormatsPriority.filter((e=>s.includes(e)))]:t.screenFormatsPriority;this.screenFormatsIterator=new kt(i.filter((s=>e.isNonNullable(t.sources[s]))).filter((t=>{switch(t){case exports.VideoFormat.DASH:return At.mse&&xt.mp4&&_t&&Dt;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return At.mse&&xt.mp4&&_t;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return At.mse&&xt.webm&&Nt.vp9&&Nt.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return At.mse&&xt.mp4&&_t;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return At.hls&&xt.mp4&&Rt;case exports.VideoFormat.HLS_JS:return At.mse&&xt.mp4&&_t&&It;case exports.VideoFormat.MPEG:return xt.mp4;default:return e.assertNever(t)}}))),this.chromecastFormatsIterator=new kt(t.chromecastFormatsPriority.filter((s=>e.isNonNullable(t.sources[s]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),s=this.chooseFormat(t);if(e.isNullable(s))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,s)}catch(e){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:e})}i?this.current$.next({type:s,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;e.assertNonNullable(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:'destroyProvider'});const t=this.params.desiredState.seekState.getState();t.state!==h.Requested&&t.state!==h.Applying||this.params.desiredState.seekState.setState({...t,state:h.Requested}),e.destroy();const s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(t,s){switch(this.log({message:`createProvider: ${t}:${s}`}),t){case o.SCREEN:return this.createScreenProvider(s);case o.CHROMECAST:return this.createChromecastProvider(s);default:return e.assertNever(t)}}createScreenProvider(t){const{sources:s,container:i,desiredState:a}=this.params,r=this.providerOutput;switch(t){case exports.VideoFormat.DASH:{const o=s[t];return e.assertNonNullable(o),new Ce({container:i,source:o,desiredState:a,output:r,config:Vt,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const o=s[t];return e.assertNonNullable(o),new ht({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const o=s[t];return e.assertNonNullable(o),new pe({container:i,source:o,desiredState:a,output:r,format:t,config:Ut,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=s[t];return e.assertNonNullable(o),new Tt({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const o=s[t];return e.assertNonNullable(o),new yt({container:i,source:o,desiredState:a,output:r,config:Ft,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const o=s[t];return e.assertNonNullable(o),new mt({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const o=s[t];return e.assertNonNullable(o),new Et({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const o=s[t];return e.assertNonNullable(o),new we({container:i,source:o,desiredState:a,output:r,config:Mt,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return e.assertNever(t)}}createChromecastProvider(t){const{sources:s,container:i,desiredState:a,meta:r}=this.params,o=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return e.assertNonNullable(n),new P({connection:n,meta:r,container:i,source:s,format:t,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(t){switch(t){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 e.assertNever(t)}}skipFormat(t){switch(t){case o.SCREEN:return this.screenFormatsIterator.next();case o.CHROMECAST:return this.chromecastFormatsIterator.next();default:return e.assertNever(t)}}handleNoFormatsError(t){switch(t){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 e.assertNever(t)}}initProviderErrorHandling(){let t=[],s=0;const i=new e.Subscription;var a;return i.add(e.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ct,position$:this.providerOutput.position$,providerChanged$:this.current$},new e.Observable((t=>{const s=new e.Subscription,i=e.timeout(a.maxTransitionInterval),r=new e.ValueSubject(void 0);e.merge(a.desiredPlaybackState$.stateChangeStarted$.pipe(e.mapTo(i)),a.desiredPlaybackState$.stateChangeEnded$.pipe(e.mapTo(void 0)),a.providerChanged$.pipe(e.map((()=>r.getValue())))).subscribe(r);const o=new e.Subscription;return s.add(o),s.add(r.subscribe((e=>{o.unsubscribe(),e&&o.add(e.subscribe(t))}))),s}))).pipe(e.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),i.add(this.providerError$.pipe(e.throttle(Ot,{leading:!1,trailing:!0})).subscribe((()=>{const i=Date.now();this.current$.getValue().destination===o.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):e.isNonNullable(t[s])&&i<t[s]+Lt?(t=[],this.switchToNextProvider()):(t[s]=i,this.reinitProvider()),s=(s+1)%Bt}))),i}}const Ht=(e,t,s)=>s*t+(1-s)*e;class jt{prevReported=void 0;slow;fast;smoothed;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(t){this.params=t,this.slow=this.fast=this.smoothed=this.prevReported=t.initial,this.smoothed$=new e.ValueSubject(t.initial),this.debounced$=new e.ValueSubject(t.initial);const s=t.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${s}`),this.smoothedSeries$=new re(`smoothed_${s}`),this.reportedSeries$=new re(`reported_${s}`)}next(t){this.slow=Ht(this.slow,t,this.params.emaAlphaSlow),this.fast=Ht(this.fast,t,this.params.emaAlphaFast);const s=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=s(this.slow,this.fast),this.smoothed$.next(this.smoothed),(e.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)),this.rawSeries$.next(t),this.smoothedSeries$.next(this.smoothed)}}var Gt;!function(e){e[e.LOCAL_STORAGE=0]='LOCAL_STORAGE',e[e.SESSION_STORAGE=1]='SESSION_STORAGE',e[e.RUNTIME=2]='RUNTIME'}(Gt||(Gt={}));const Yt=new Map;let Qt=Gt.RUNTIME;const zt=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(zt,'test'),localStorage.removeItem(zt),Qt=Gt.LOCAL_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;try{sessionStorage.getItem(zt),Qt=Gt.SESSION_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;Qt=Gt.RUNTIME}}})();const Wt=(t,s)=>{switch(Qt){case Gt.LOCAL_STORAGE:try{localStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Gt.SESSION_STORAGE:try{sessionStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case Gt.RUNTIME:return void Yt.set(t,s);default:e.assertNever(Qt)}},Jt=window.navigator.connection,Kt=()=>{const t=Jt?.downlink;if(e.isNonNullable(t)&&10!==t)return 1e3*t},Xt=()=>{const t=Jt?.rtt;if(e.isNonNullable(t)&&3e3!==t)return t},Zt=(e,t,s)=>{const i=8*s;return i/(i/e+t)};class es{throughput;rtt;subscription=new e.Subscription;tuningConfig;throughput$;rtt$;rttAdjustedThroughput$;constructor(t){this.tuningConfig=t;const s=es.load('one_video_throughput')||(t.useBrowserEstimation?Kt():void 0)||5e3,i=es.load('one_video_rtt')??(t.useBrowserEstimation?Xt():void 0)??0;if(this.throughput$=new e.ValueSubject(s),this.rtt$=new e.ValueSubject(i),this.rttAdjustedThroughput$=new e.ValueSubject(Zt(s,i,t.rttPenaltyRequestSize)),this.throughput=new jt({initial:s,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new jt({initial:i,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:1,label:'rtt'}),t.useBrowserEstimation){const t=()=>{const t=Kt();t&&this.throughput.next(t);const s=Xt();e.isNonNullable(s)&&this.rtt.next(s)};Jt&&'onchange'in Jt&&this.subscription.add(e.fromEvent(Jt,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((e=>{Wt('one_video_throughput',e.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((e=>{Wt('one_video_rtt',e.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(e.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(e.map((({throughput:e,rtt:s})=>Zt(e,s,t.rttPenaltyRequestSize))),e.filter((e=>{const s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(e-s)/s>=t.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(t){let s=0,i=e.now();const a=new e.Subscription;switch(this.subscription.add(a),t.readyState){case 4:break;case 3:case 2:a.add(e.fromEvent(t,'progress').pipe(e.once()).subscribe((t=>{s=t.loaded,i=e.now()})));break;case 1:case 0:a.add(e.fromEvent(t,'loadstart').subscribe((()=>{s=0,i=e.now()})))}a.add(e.fromEvent(t,'loadend').subscribe((r=>{if(200===t.status){const t=r.loaded,a=e.now(),o=t-s,n=a-i;this.addRawSpeed(o,n)}a.unsubscribe()})))}trackStream(t){const s=t.getReader();if(!s)return void t.cancel('Could not get reader');let i=0;const a=e.now();let r=0,o=e.now();const n=e=>{s.releaseLock(),t.cancel(`Throughput Estimator error: ${e}`).catch((()=>{}))},d=async({done:t,value:u})=>{t?this.addRawSpeed(i,e.now()-a):u&&(i+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&e.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,e.now()-o),r=0,o=e.now()),await(s?.read().then(d,n)))};s?.read().then(d,n)}addRawSpeed(e,t){if(es.sanityCheck(e,t)){const s=8*e/t;this.throughput.next(s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=8*e/t;return!(!s||!isFinite(s))&&(!(s>1e6)&&(!(s<30)&&(!(e<10240)&&!(t<=20))))}static load(t){const s=(t=>{switch(Qt){case Gt.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case Gt.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case Gt.RUNTIME:return Yt.get(t);default:e.assertNever(Qt)}})(t);if(e.isNonNullable(s))return parseInt(s,10)??void 0}}const ts={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.2,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!1},dash:{extraInitSize:1e3,forwardBufferTarget:3e4,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_SEP_VK],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1};const ss=(t=(e=>e))=>({playbackState:s,seekState:i,playbackAbort$:a,looped$:r,position$:o})=>new e.Observable((n=>{let d;const u=s.transitionEnded$.pipe(e.filter((e=>(e.from===exports.PlaybackState.PAUSED||e.from===exports.PlaybackState.STOPPED)&&e.to===exports.PlaybackState.PLAYING))),c=s.stateChangeEnded$.pipe(e.filter((e=>e.from===exports.PlaybackState.PLAYING&&e.to===exports.PlaybackState.PAUSED))),l=i.stateChangeEnded$.pipe(e.filter((({to:e})=>e.state===h.Requested&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),p=i.stateChangeEnded$.pipe(e.filter((({from:e,to:t})=>e.state===h.Applying&&t.state===h.None&&(s.getTransition()?.from??s.getState())===exports.PlaybackState.PLAYING))),m=e.merge(u,p).pipe(e.map((()=>t(o.getValue())))),S=e.merge(e.merge(c,l,a).pipe(e.map((()=>t(o.getValue())))),r.pipe(e.map(t)));return(new e.Subscription).add(m.subscribe((e=>{d=t(e)}))).add(S.subscribe((s=>{const i=t(s);if(e.isNullable(d)||d===i)return;const a={start:d,end:i};d=void 0,n.next(a)})))})),is=ss((e=>e)),as=ss((e=>Math.round(1e3*e)+Date.now())),rs={[o.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,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 e.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return e.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return e.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return e.ValueSubject}}),exports.Player=class{subscription=new e.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new e.Logger;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;desiredState={playbackState:new k(exports.PlaybackState.STOPPED),seekState:new k({state:h.None}),volume:new k({volume:1,muted:!1}),videoTrack:new k(void 0),autoVideoTrackSwitching:new k(!0),autoVideoTrackLimits:new k({}),isLooped:new k(!1),externalTextTracks:new k([]),currentTextTrack:new k(void 0),textTrackCuesSettings:new k({})};info={playbackState$:new e.ValueSubject(exports.PlaybackState.STOPPED),position$:new e.ValueSubject(0),duration$:new e.ValueSubject(1/0),muted$:new e.ValueSubject(!1),volume$:new e.ValueSubject(1),availableQualities$:new e.ValueSubject([]),availableQualitiesFps$:new e.ValueSubject({}),currentQuality$:new e.ValueSubject(void 0),isAutoQualityEnabled$:new e.ValueSubject(!0),autoQualityLimitingAvailable$:new e.ValueSubject(!1),autoQualityLimits$:new e.ValueSubject({}),currentBuffer$:new e.ValueSubject(void 0),isBuffering$:new e.ValueSubject(!0),isStalled$:new e.ValueSubject(!1),isEnded$:new e.ValueSubject(!1),isLooped$:new e.ValueSubject(!1),isLive$:new e.ValueSubject(void 0),liveTime$:new e.ValueSubject(void 0),currentFormat$:new e.ValueSubject(void 0),availableTextTracks$:new e.ValueSubject([]),currentTextTrack$:new e.ValueSubject(void 0),throughputEstimation$:new e.ValueSubject(void 0),rttEstimation$:new e.ValueSubject(void 0),videoBitrate$:new e.ValueSubject(void 0),hostname$:new e.ValueSubject(void 0),httpConnectionType$:new e.ValueSubject(void 0),httpConnectionReused$:new e.ValueSubject(void 0),chromecastState$:new e.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new e.ValueSubject(void 0),intrinsicVideoSize$:new e.ValueSubject(void 0)};events={started$:new e.Subject,startAttempt$:new e.Subject,willPause$:new e.Subject,willResume$:new e.Subject,willDestruct$:new e.Subject,watchCoverageRecord$:new e.Subject,watchCoverageLive$:new e.Subject,managedError$:new e.Subject,fatalError$:new e.Subject,ended$:new e.Subject,looped$:new e.Subject,seeked$:new e.Subject,willSeek$:new e.Subject,firstBytes$:new e.Subject,firstFrame$:new e.Subject,log$:new e.Subject};experimental={element$:new e.ValueSubject(void 0),enableDebugTelemetry$:new e.ValueSubject(!1),dumpTelemetry:ie};constructor(e={}){if(this.initLogs(),this.tuning=(e=>{const t={};for(const s of Object.keys(ts)){const i=ts[s],a=e[s];Array.isArray(i)&&Array.isArray(a)?t[s]=a:t[s]='object'==typeof i&&'object'==typeof a?{...i,...a}:a??i}return t})(e),this.chromecastInitializer=new c({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new es(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(e,t,s)=>{const i=Reflect.get(e,t,s);return'function'!=typeof i?i:(...s)=>{try{return i.apply(e,s)}catch(e){const i=s.map((e=>JSON.stringify(e,((e,t)=>{const s=typeof t;return['number','string','boolean'].includes(s)?t:null===t?null:`<${s}>`})))),a=`Player.${String(t)}`,r=`Exception calling ${a} (${i.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:e}),e}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const s='string'==typeof t.container?document.getElementById(t.container):t.container;return e.assertNonNullable(s,`Wrong container or containerId {${t.container}}`),s})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new qt({screenFormatsPriority:[...rs[o.SCREEN].live,...rs[o.SCREEN].vod],chromecastFormatsPriority:[...rs[o.CHROMECAST].live,...rs[o.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:h.Requested,position:1e3*e,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e),this}setVolume(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(t){e.assertNonNullable(this.providerContainer);const s=this.providerContainer.providerOutput.availableVideoTracks$.getValue();s.length||(this.explicitInitialQuality=t);const i=s.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map((e=>({type:'external',...e})))),this}selectTextTrack(e){return(void 0===e||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((t=>t.id===e)))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){e.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(e.isNullable(t))return this.info.position$.getValue();const s=this.desiredState.seekState.getState(),i=s.state===h.None?void 0:s.position;return e.isNonNullable(i)?i/1e3:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(e.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(e.map((e=>e.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.autoQualityLimits$));const t=new e.Subscription;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING||e.to===exports.PlaybackState.PAUSED)),e.debounce(0),e.once()).subscribe((e=>{const t=e.to===exports.PlaybackState.PLAYING,s=this.info.muted$.getValue(),i=t?s?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(i)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((e=>e.to===exports.PlaybackState.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const e=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(e)}}))).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()}})))}initProviderContainerSubscription(t){this.subscription.add(t.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekState.getState();e.state===h.Requested?this.desiredState.seekState.setState({...e,state:h.Applying}):this.events.managedError$.next({id:`WillSeekIn${e.state}`,message:'Received unexpeceted willSeek$'})}))).add(t.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===h.Applying&&(this.desiredState.seekState.setState({state:h.None}),this.events.seeked$.next())}))).add(t.current$.pipe(e.map((e=>e.type))).subscribe(this.info.currentFormat$)).add(t.current$.pipe(e.map((e=>e.destination)),e.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(t.providerOutput.availableVideoTracks$.pipe(e.map((e=>e.map((({quality:e})=>e)).sort(((e,t)=>E(e)?1:E(t)?-1:g(t,e)?1:-1))))).subscribe(this.info.availableQualities$)).add(t.providerOutput.availableVideoTracks$.subscribe((e=>{const t={};for(const s of e)s.fps&&(t[s.quality]=s.fps);this.info.availableQualitiesFps$.next(t)}))).add(t.providerOutput.currentVideoTrack$.subscribe((e=>{this.info.currentQuality$.next(e?.quality),this.info.videoBitrate$.next(e?.bitrate);const s=t.providerOutput.element$.getValue();s&&this.info.intrinsicVideoSize$.next({width:s.videoWidth,height:s.videoHeight})}))).add(t.providerOutput.hostname$.pipe(e.filterChanged()).subscribe(this.info.hostname$)).add(t.providerOutput.httpConnectionType$.pipe(e.filterChanged()).subscribe(this.info.httpConnectionType$)).add(t.providerOutput.httpConnectionReused$.pipe(e.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(t.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(t.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(t.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(t.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(t.providerOutput.duration$.subscribe(this.info.duration$)).add(t.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(t.providerOutput.isLive$.subscribe(this.info.isLive$)).add(t.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(t.providerOutput.volume$.pipe(e.map((e=>e.muted)),e.filterChanged()).subscribe(this.info.muted$)).add(t.providerOutput.volume$.pipe(e.map((e=>e.volume)),e.filterChanged()).subscribe(this.info.volume$)).add((({seekState:t,position$:s})=>e.merge(t.stateChangeEnded$.pipe(e.map((({to:e})=>e.state===h.None?void 0:(e.position??NaN)/1e3)),e.filter(e.isNonNullable)),s.pipe(e.filter((()=>t.getState().state===h.None)))))({seekState:this.desiredState.seekState,position$:t.providerOutput.position$}).subscribe(this.info.position$)).add(e.merge(t.providerOutput.endedEvent$.pipe(e.mapTo(!0)),t.providerOutput.seekedEvent$.pipe(e.mapTo(!1))).pipe(e.filterChanged()).subscribe(this.info.isEnded$)).add(t.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(t.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(t.providerError$.subscribe(this.events.managedError$)).add(t.noAvailableProvidersError$.pipe(e.map((e=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(t.providerOutput.element$.subscribe(this.experimental.element$)).add(t.providerOutput.firstBytesEvent$.subscribe(this.events.firstBytes$)).add(t.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const s=new e.ValueSubject(!1);this.subscription.add(t.providerOutput.seekedEvent$.subscribe((()=>s.next(!1)))).add(t.providerOutput.willSeekEvent$.subscribe((()=>s.next(!0))));const i=new e.ValueSubject(!0);this.subscription.add(t.current$.subscribe((()=>i.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(e.filter((({to:e})=>e===exports.PlaybackState.PLAYING)),e.once()).subscribe((()=>i.next(!1))));let a=0;const r=e.merge(t.providerOutput.isBuffering$,s,i).pipe(e.map((()=>{const e=t.providerOutput.isBuffering$.getValue(),a=s.getValue()||i.getValue();return e&&!a})),e.filterChanged());this.subscription.add(r.subscribe((e=>{e?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const o=new e.Subscription;this.subscription.add(o);const n=e.merge(e.fromEvent(window,'beforeunload'),this.events.willDestruct$,t.current$.pipe(e.filter((e=>Boolean(e?.provider)))));t.providerOutput.isLive$.pipe(e.filterChanged()).subscribe((t=>{switch(e.assertNonNullable(this.providerContainer),o.unsubscribe(),t){case!0:o.add(as({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:o.add(is({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(e.map((e=>e?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const s=new e.Subscription;this.subscription.add(s),this.subscription.add(t.current$.pipe(e.filterChanged(((e,t)=>e.provider===t.provider))).subscribe((()=>{s.unsubscribe(),s.add(t.providerOutput.availableVideoTracks$.pipe(e.filter((e=>e.length>0)),e.once()).subscribe((e=>{this.setStartingVideoTrack(e)})))})))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find((({quality:e})=>e===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),t||(t=ne(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(e.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(e.map((e=>({transition:e,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(e.map((e=>({transition:e,entity:'playbackState',type:'end'}))))).pipe(e.map((e=>({component:'desiredState',message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const t=this.providerContainer?.providerOutput;e.assertNonNullable(this.providerContainer),e.assertNonNullable(t),se={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((e=>{te=e})),this.providerContainer.current$.subscribe((({type:e})=>ae('provider',e))),t.duration$.subscribe((e=>ae('duration',e))),t.availableVideoTracks$.pipe(e.filter((e=>!!e.length)),e.once()).subscribe((e=>ae('tracks',e))),this.events.fatalError$.subscribe(new re('fatalError')),this.events.managedError$.subscribe(new re('managedError')),t.position$.subscribe(new re('position')),t.currentVideoTrack$.pipe(e.map((e=>e?.quality))).subscribe(new re('quality')),t.currentBuffer$.subscribe(new re('buffer')),t.isBuffering$.subscribe(new re('isBuffering'))].forEach((e=>this.subscription.add(e))),ae('codecs',Object.keys(Nt).filter((e=>Nt[e])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.50';
|