@vkontakte/videoplayer-core 2.0.74 → 2.0.75-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.74
3
- * Thu, 10 Nov 2022 11:13:43 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-74/doc/
2
+ * @vkontakte/videoplayer-core v2.0.75-beta.0
3
+ * Fri, 02 Dec 2022 09:44:42 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-75/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.js'));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',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_ONDEMAND_VK='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS',r.HLS_LIVE='HLS_LIVE',r.WEB_RTC_LIVE='WEB_RTC_LIVE',function(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;const i=e.isNonNullable(window.chrome?.cast),a=Boolean(window.__onGCastApiAvailable);var r;i?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{delete window.__onGCastApiAvailable,e&&this.initializeCastApi()},a||(r='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',r),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 w;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(w||(w={}));class ${subscription=new e.Subscription;loadMediaTimeoutSubscription=new e.Subscription;videoState=new k(w.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_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return 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(w.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(w.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!==w.PAUSED&&e!==w.PLAYING||(this.videoState.setState(w.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==w.PLAYING&&e!==w.PAUSED||(this.videoState.setState(w.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===w.READY&&this.videoState.setState(w.READY)}handleRemoteStop(){this.videoState.getState()!==w.STOPPED&&this.videoState.setState(w.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_ONDEMAND: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:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_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}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');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===w.STOPPED)switch(i){case exports.PlaybackState.PLAYING:switch(t){case w.PLAYING:break;case w.PAUSED:case w.READY:this.videoState.startTransitionTo(w.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case w.PLAYING:this.videoState.startTransitionTo(w.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case w.PAUSED:break;case w.READY:this.videoState.startTransitionTo(w.PAUSED),this.videoState.setState(w.PAUSED);break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(i)}else this.seek(r.position)}else t!==w.STOPPED&&(this.videoState.startTransitionTo(w.STOPPED),this.stop())}}class P{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 P{constructor(){super(),this.listeners||P.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 R=N({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),D=R?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;R?D.Request:window.Request;const C=R?x:window.AbortController,I=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]=I(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(I),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 C,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 _(o,{signal:d}).then((e=>{if(u.response=e,!e.ok||!e.body)return void this.onBigRequestError(u);const[t,s]=e.body.tee();this.params.onDownloadStream?.(s);const r=t.getReader(),o=parseInt(e.headers.get('Content-Length')??'',10)||a-i+1;u.data=new ArrayBuffer(o);const n=new Uint8Array(u.data),d=async({done:e,value:t})=>{e?this.onBigRequestProgress(u):t&&(n.set(t,u.loaded),u.loaded+=t.byteLength,this.onBigRequestProgress(u),await(r?.read().then(d,L.suppressStreamErrors).catch(h)))};r?.read().then(d,L.suppressStreamErrors).catch(h)}),L.suppressAbort).catch((e=>this.onBigRequestError(u,e))),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a,response:r}){if(!this.activeRequests.has(e)||!a)return;const o=this.dashJsRequestQueue.get(e)??[];for(const n of o){const{request:o}=n,[d,u]=I(o),h=d>=t&&u<=t+i,c=t>=d&&t+i<u,l=a.slice(d-t,Math.min(u-t+1,i));if((h||c)&&(o.requestStartDate=o.requestStartDate??new Date,o.firstByteDate=o.firstByteDate??new Date,o.bytesLoaded=l.byteLength,o.bytesTotal=s-t),h){o.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter((e=>e!==n))),n.success?.(l,'',e);const t=r?Array.from(r.headers.entries()).map((([e,t])=>`${e}: ${t}`)).join('\r\n'):'';this.dashMetrics?.addHttpRequest(o,e,r?.status??200,t,[])}else c&&n.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]=I(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]=I(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 M=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)},V=t=>{const s=new e.ValueSubject(1/0),i=new e.Subject,a=new e.ValueSubject(void 0),r=new e.ValueSubject(void 0);let o=NaN,n=!1;return t.extend('XHRLoader',(function(){const{parent:t}=this,d=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const d=t.onload,u=t.progress;t.onload=function(...t){return(t=>{const i=Object.fromEntries(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((e=>e.split(': '))));if('x-playback-duration'in i||'x-playback-duration-millis'in i){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)}const o=i['x-delivery-type']??exports.HttpConnectionType.HTTP1,n={1:!0,0:!1}[i['x-reused']]??void 0;a.next(o),r.next(n)})(this),d(...t)},t.progress=function(...e){return this.readyState>=2&&!n&&(n=!0,i.next(Date.now()-o)),u(...e)},o=Date.now(),n=!1}return d(t)}}}),!0),{playbackDuration$:s,ping$:i,connectionReused$:r,connectionType$:a}},U=e=>{const t=new URL(e);return t.searchParams.set('quic','1'),t.toString()},F=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=(t,s,i,a)=>q(s,(()=>t.playbackRate),(s=>{e.isNonNullable(s)&&(t.playbackRate=s)}),{changed$:i,onError:a}),Y=(e,t)=>{if(e.id===t)return!0;const[s,i,a]=t.split('|');return e.language===i&&e.label===a};class Q{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(Q.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)&&Y(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 z=e=>{const t=document.createElement('video');return t.setAttribute('crossorigin','anonymous'),t.setAttribute('playsinline','playsinline'),e.appendChild(t),t};class W{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}}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({from:s,to:i,i:t})}return this._buffer.sort((function(e,t){return e.from-t.from})),this._buffer}getByTime(e){return this._buffer.find((t=>e>=t.from&&e<t.to))}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(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((({from:i,to: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 X=(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{from:i,to: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{from:i,to:a}};const K=t=>{const s=s=>e.fromEvent(t,s).pipe(e.mapTo(void 0)),i=e.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((s=>e.fromEvent(t,s)))).pipe(e.map((e=>'ended'===e.type?t.readyState<2:t.readyState<3)),e.filterChanged()),a=e.merge(e.fromEvent(t,'progress'),e.fromEvent(t,'timeupdate')).pipe(e.map((()=>X(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,'ratechange').pipe(e.map((()=>t.playbackRate))),n=e.fromEvent(t,'error').pipe(e.filter((()=>Boolean(t.error||t.src))),e.map((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),d=e.fromEvent(t,'timeupdate').pipe(e.map((()=>t.currentTime))),u=new e.Subject;let h;return d.subscribe((s=>{t.loop&&e.isNonNullable(h)&&e.isNonNullable(s)&&h>=t.duration-.3&&s<=.3&&u.next(h),h=s})),{playing$:s('playing'),pause$:s('pause').pipe(e.filter((()=>!t.error))),canplay$:s('canplay'),ended$:s('ended'),looped$:u,error$:n,seeked$:s('seeked'),seeking$:s('seeking'),progress$:s('progress'),loadStart$:s('loadstart'),loadedMetadata$:s('loadedmetadata'),loadedData$:s('loadeddata'),timeUpdate$:d,durationChange$:e.fromEvent(t,'durationchange').pipe(e.map((()=>t.duration))),isBuffering$:i,currentBuffer$:a,volumeState$:r,playbackRateState$:o}},Z=e=>{if(e.includes('/')){const t=e.split('/');return parseInt(t[0])/parseInt(t[1])}return parseFloat(e)};let ee=!1,te={};const se=e=>{e(te)},ie=(e,t)=>{ee&&(te.meta=te.meta??{},te.meta[e]=t)};class ae{name;constructor(e){this.name=e}next(e){if(!ee)return;te.series=te.series??{};const t=te.series[this.name]??[];t.push([Date.now(),e]),te.series[this.name]=t}}const re=new ae('best_bitrate');class oe{last;history={};recordSelection(t){this.history[t.id]=e.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ne=(t,{container:s,throughput:i,tuning:a,limits:r,reserve:o=0,forwardBufferHealth:n,playbackRate:d,current:u,history:h})=>{const c=a.usePixelRatio?window.devicePixelRatio??1:1,l=a.limitByContainer&&s&&s.width>0&&s.height>0&&{width:s.width*c*a.containerSizeFactor,height:s.height*c*a.containerSizeFactor},p=l&&T(l),m=a.considerPlaybackRate&&e.isNonNullable(d)?d:1,S=t.filter((e=>!E(e.quality))).sort(((e,t)=>g(e.quality,t.quality)?-1:1)),f=S.at(-1)?.quality,y=S.at(0)?.quality,k=e.isNullable(r)||e.isNonNullable(r.min)&&e.isNonNullable(r.max)&&v(r.max,r.min)||e.isNonNullable(r.min)&&y&&g(r.min,y)||e.isNonNullable(r.max)&&f&&v(r.max,f),w=m*($=n??.5,P=a.bitrateFactorAtEmptyBuffer,A=a.bitrateFactorAtFullBuffer,(P-A)*Math.pow(2,-10*$)+A);var $,P,A;const x=S.filter((t=>{const s=!p||v(t.quality,p),d=!(e.isNonNullable(i)&&isFinite(i)&&e.isNonNullable(t.bitrate))||i-o>=t.bitrate*w,h=a.lazyQualitySwitch&&e.isNonNullable(a.minBufferToSwitchUp)&&u&&!E(u.quality)&&(n??0)<a.minBufferToSwitchUp&&g(t.quality,u.quality),c=k||(e.isNullable(r.max)||(l=t.quality,m=r.max,b[l].height<=b[m].height))&&(e.isNullable(r.min)||((e,t)=>b[e].height>=b[t].height)(t.quality,r.min));var l,m;return s&&d&&!h&&c}))[0];x&&x.bitrate&&re.next(x.bitrate);const N=x??S[Math.ceil((S.length-1)/2)]??t[0],R=N&&h&&h.history[N.id]&&e.now()-h.history[N.id]<=a.trackCooldown&&(!h.last||N.id!==h.last.id);if(N?.id&&h&&!R&&h.recordSelection(N),R&&h?.last){const e=h.last;return h?.recordSwitch(e),e}return h?.recordSwitch(N),N};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 Q;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 W;destroyBigRequest;constructor(e){this.video=z(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?Z(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&&F(this.player),M(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:U})),!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'),(({mediaType:e,request:{url:s}})=>{const i=this.player.getDashMetrics(),a=i.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),r=i.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type')??exports.HttpConnectionType.HTTP1,o={1:!0,0:!1}[a]??void 0;this.params.output.httpConnectionType$.next(r),this.params.output.httpConnectionReused$.next(o),t.hostname$.next(de(s))})),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((()=>X(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,connectionType$:u,connectionReused$:h}=V(this.player);a(u,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(n,this.maxSeekBackTime$),a(d.pipe(e.once()),t.firstBytesEvent$),a(le(this.player,'canPlay'),t.canplay$),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((()=>{this.subscription.add(le(this.player,'playbackPlaying').pipe(e.once(),e.mapTo(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(H(this.video,s.isLooped,i));const{volumeState$:c,looped$:l,playbackRateState$:p}=K(this.video);this.subscription.add(j(this.video,s.volume,c,i)),this.subscription.add(c.subscribe(t.volume$,i)),this.subscription.add(l.subscribe(t.loopedEvent$)),this.subscription.add(G(this.video,s.playbackRate,p,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(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.maxParallelRequests,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=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=t;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=i.dur.length-1;for(;r>=0&&(a-=i.dur[r],!(a<=0));--r);e=Math.min(r,i.dur.length-1-s),e=Math.max(e,0)}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(),w(),k())}))};i>0?S=window.setTimeout((()=>{this.paused?k():a()}),i):a()},w=()=>{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()},$=(e,t)=>{if(!c()||!this.sourceBuffer)return;let s,r,o;const n=s=>{window.setTimeout((()=>{c()&&$(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)}}},P=()=>{d&&n&&(a([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),$(d,(function(){d=null,w()})))},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}P()}}),(()=>this._handleNetworkError()))},N=t=>{c()&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(t),!1)))},R=e=>{c()&&(t.cachedHeader=e,$(e,(()=>{n=!0,P()})))};r=!0,T.seek((t=>{c()&&(E=fe(),t?(m=t,!e.isNullable(s)||t.startTS>s?x(t):(h=t,w())):k())}),s),t.cachedHeader?R(t.cachedHeader):l(t.headerUrl,R,(()=>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 we=[ke.PAUSED,ke.PLAYING,ke.READY],$e=[ke.PAUSED,ke.PLAYING,ke.READY];class Pe{subscription=new e.Subscription;video;videoState=new k(ke.STOPPED);dash;representations$=new e.ValueSubject([]);textTracksManager=new Q;maxSeekBackTime$=new e.ValueSubject(1/0);zeroTime$=new e.ValueSubject(void 0);liveOffset=new W;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=z(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=K(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(G(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,s)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max: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:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger: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($e.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&&we.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 Re{_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(Re._str2ua(e.substr(n))),n=e.length};let p=e.baseURL+'&bytes='+t+'-'+s;this._params.requestQuic&&(p=U(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=Re._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=U(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?Z(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.to-this._video.currentTime,r<e.bufferLength&&(this._onDashCallback('buffering'),a!==t.to&&(a=t.to,window.setTimeout((()=>{try{const e=this._buffer.getNextWithGap(t);e&&(this._video.currentTime=e.from)}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 Re({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.to+a){const t=this._findRef(i.toTime);t&&t.toTime<s.to+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 _e;!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'}(_e||(_e={}));const Ce=[_e.PAUSED,_e.PLAYING];class Ie{videoState=new k(_e.STOPPED);subscription=new e.Subscription;video;buffer;dash;representations$=new e.ValueSubject([]);currentRepresentation$=new e.ValueSubject(void 0);params;textTracksManager=new Q;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=z(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=K(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.playing$,t.firstFrameEvent$),o(r.canplay$,t.canplay$),this.subscription.add(r.seeking$.subscribe((()=>{e.isNullable(this.params.desiredState.seekState.getState().state!==h.Applying)&&(this.videoState.getState()===_e.PLAYING||this.videoState.getState()===_e.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.subscription.add(G(this.video,s.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,s,t),o(ue(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===_e.READY&&this.videoState.setState(_e.READY)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(_e.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(_e.PLAYING),f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),i)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(_e.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=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(e/i,1);u=ne(s.map((({track:e})=>e)),{container:n,throughput:o,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:s.find((({representation:e})=>e===t))?.track})?.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===_e.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(e.filter(e.isNonNullable))}).pipe(e.once()).subscribe((()=>this.videoState.setState(_e.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(),e.mapTo(void 0)).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(_e.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(_e.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&&Ce.includes(t)&&this.seek(r.position,r.forcePrecise),t){case _e.STOPPED:return this.videoState.startTransitionTo(_e.MANIFEST_LOADED),void this.prepare();case _e.MANIFEST_LOADED:return void this.videoState.startTransitionTo(_e.INITIAL_REPRESENTATION_SELECTED);case _e.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(_e.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case _e.METADATA_LOADED:return this.videoState.startTransitionTo(_e.READY),void this.dash.updateRefsForCurrentTime();case _e.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(_e.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(_e.PLAYING),this.playIfAllowed()));case _e.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(_e.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case _e.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(_e.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==_e.STOPPED&&(this.videoState.startTransitionTo(_e.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(_e.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))}}var Le,Be,Oe,Me,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.BYTE_RANGE='byteRange',e.TEMPLATE='template'}(Oe||(Oe={})),function(e){e.NONE='none',e.DOWNLOADING='downloading',e.DOWNLOADED='downloaded',e.PARTIALLY_FED='partially_fed',e.FED='fed'}(Me||(Me={})),function(e){e.MP4='mp4',e.WEBM='webm'}(Ve||(Ve={}));var Ue=(e,t)=>{for(let s=0;s<e.length;s++){if(1e3*e.start(s)<=t&&1e3*e.end(s)>t)return!0}return!1};const Fe='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(e,t={})=>{const s=t.timeout||1,i=performance.now();return window.setTimeout((()=>{e({get didTimeout(){return!t.timeout&&performance.now()-i-1>s},timeRemaining:()=>Math.max(0,performance.now()-i+1)})}),1)}:window.requestIdleCallback;var qe=()=>{const{userAgent:e}=window.navigator;return!/chrome/i.test(e)&&/webkit|safari|khtml/i.test(e)};let He=!1;try{He=qe()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??'',10)<16}catch(e){console.error(e)}class je{bufferFull$=new e.Subject;error$=new e.Subject;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener('updateend',this.completeTask)}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()}))}async abort(e){return new Promise((t=>{let s;s=He&&e?{operation:'safariAbort',init:e,callback:t}:{operation:'abort',callback:t};for(const{callback:e}of this.queue)e(!1);s&&(this.queue=[s]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}completeTask=()=>{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:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(e){e instanceof DOMException&&'QuotaExceededError'===e.name&&'append'===t&&this.bufferFull$.next(this.currentTask.data.byteLength),e instanceof DOMException&&'InvalidStateError'===e.name&&'remove'===t||this.error$.next({id:`BufferTaskQueue:${t}`,message:'Buffer operation failed',thrown:e}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(t){const{operation:s}=t;switch(s){case'append':this.buffer.appendBuffer(t.data);break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(t.init);break;default:e.assertNever(s)}}}var Ge;!function(e){e[e.HEADER=0]='HEADER',e[e.PARAM=1]='PARAM'}(Ge||(Ge={}));class Ye{throughputEstimator;requestQuic;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);abortAllController=new C;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=U(t));const s=yield _(t,{signal:this.abortAllController.signal}).catch(Qe);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=e.abortable(this.abortAllController.signal,async function*(t,{rangeMethod:s=Ge.HEADER,range:i,onProgress:a,priority:r='auto',signal:o,measureThroughput:n=!0}={}){let d=t;const u=new Headers;if(i)switch(s){case Ge.HEADER:u.append('Range',`${i.from}-${i.to}`);break;case Ge.PARAM:{const e=new URL(d,location.href);e.searchParams.append('bytes',`${i.from}-${i.to}`),d=e.toString();break}default:e.assertNever(s)}this.requestQuic&&(d=U(d));let h=this.abortAllController.signal;if(o){const t=new C;if(this.subscription.add(e.merge(e.fromEvent(this.abortAllController.signal,'abort'),e.fromEvent(o,'abort')).subscribe((()=>{try{t.abort()}catch(e){Qe(e)}}))),this.abortAllController.signal.aborted||o.aborted)try{t.abort()}catch(e){Qe(e)}h=t.signal}const c=e.now(),l=yield _(d,{priority:r,headers:u,signal:h}).catch(Qe),p=e.now();if(this.throughputEstimator?.addRawRtt(p-c),!l)return null;if(!l.ok||!l.body)return Promise.reject(new Error(`Fetch error ${l.status}: ${l.statusText}`));this.onHeadersReceived(l.headers);const m=parseInt(l.headers.get('Content-Length')??'',10)||i&&i.to-i.from+1||NaN;if(!m){const t=yield l.arrayBuffer();return this.throughputEstimator?.addRawSpeed(t.byteLength,e.now()-p),a?.(new DataView(t),t.byteLength),t}if(!a&&!n)return l.arrayBuffer();const[S,f]=l.body.tee(),b=S.getReader();n&&this.throughputEstimator?.trackStream(f);let g=0;const v=new ArrayBuffer(m),y=new Uint8Array(v),T=new DataView(v);let E=!1;const k=e=>{E=!0,Qe(e)},w=e.abortable(h,async function*({done:t,value:s}){0===g&&this.lastRequestFirstBytes$.next(e.now()-c),h.aborted||(t?a?.(T,g):s&&(y.set(s,g),g+=s.byteLength,a?.(T,g),yield b?.read().then(w,k)))}.bind(this));return yield b?.read().then(w,k),E?null:v}.bind(this));async fetchRepresentation(t,s,i='auto'){const{type:a}=t;switch(a){case Oe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(t,s,i)??null;case Oe.TEMPLATE:return await this.fetchTemplateRepresentation(t,i)??null;default:e.assertNever(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=e.abortable(this.abortAllController.signal,async function*(e,t,s){if(e.type!==Oe.BYTE_RANGE)return null;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);const h=yield this.fetch(e.url,{rangeMethod:Ge.PARAM,range:{from:n,to:d},priority:s,measureThroughput:!1});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 i=t.getIndexRange(l);if(i){const t=yield this.fetch(e.url,{rangeMethod:Ge.PARAM,range:i,priority:s,measureThroughput:!1});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));fetchTemplateRepresentation=e.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==Oe.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});if(!i)return null;return{segments:e.segments.map((e=>({...e,status:Me.NONE,size:void 0}))),dataView:new DataView(i)}}.bind(this))}const Qe=e=>{if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e},ze=new TextDecoder('ascii'),We=e=>{let t=0,s=e.getUint32(t);t+=4;const i=new DataView(e.buffer,e.byteOffset+t,4),a=ze.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)}},Je={validateData:e=>'ftyp'===ze.decode(new DataView(e.buffer,e.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:e=>{const t=We(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=4294967295&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:Me.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=We(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 Xe,Ke;!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'}(Xe||(Xe={})),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'}(Ke||(Ke={}));const Ze={[Xe.EBML]:{type:Ke.Master},[Xe.EBMLVersion]:{type:Ke.UnsignedInteger},[Xe.EBMLReadVersion]:{type:Ke.UnsignedInteger},[Xe.EBMLMaxIDLength]:{type:Ke.UnsignedInteger},[Xe.EBMLMaxSizeLength]:{type:Ke.UnsignedInteger},[Xe.DocType]:{type:Ke.String},[Xe.DocTypeVersion]:{type:Ke.UnsignedInteger},[Xe.DocTypeReadVersion]:{type:Ke.UnsignedInteger},[Xe.Void]:{type:Ke.Binary},[Xe.Segment]:{type:Ke.Master},[Xe.SeekHead]:{type:Ke.Master},[Xe.Seek]:{type:Ke.Master},[Xe.SeekID]:{type:Ke.Binary},[Xe.SeekPosition]:{type:Ke.UnsignedInteger},[Xe.Info]:{type:Ke.Master},[Xe.TimestampScale]:{type:Ke.UnsignedInteger},[Xe.Duration]:{type:Ke.Float},[Xe.Tracks]:{type:Ke.Master},[Xe.Chapters]:{type:Ke.Master},[Xe.Cluster]:{type:Ke.Master},[Xe.Timestamp]:{type:Ke.UnsignedInteger},[Xe.SilentTracks]:{type:Ke.Master},[Xe.SilentTrackNumber]:{type:Ke.UnsignedInteger},[Xe.Position]:{type:Ke.UnsignedInteger},[Xe.PrevSize]:{type:Ke.UnsignedInteger},[Xe.SimpleBlock]:{type:Ke.Binary},[Xe.BlockGroup]:{type:Ke.Master},[Xe.EncryptedBlock]:{type:Ke.Binary},[Xe.Attachments]:{type:Ke.Master},[Xe.Tags]:{type:Ke.Master},[Xe.Cues]:{type:Ke.Master},[Xe.CuePoint]:{type:Ke.Master},[Xe.CueTime]:{type:Ke.UnsignedInteger},[Xe.CueTrackPositions]:{type:Ke.Master},[Xe.CueTrack]:{type:Ke.UnsignedInteger},[Xe.CueClusterPosition]:{type:Ke.UnsignedInteger},[Xe.CueRelativePosition]:{type:Ke.UnsignedInteger},[Xe.CueDuration]:{type:Ke.UnsignedInteger},[Xe.CueBlockNumber]:{type:Ke.UnsignedInteger},[Xe.CueCodecState]:{type:Ke.UnsignedInteger},[Xe.CueReference]:{type:Ke.Master},[Xe.CueRefTime]:{type:Ke.UnsignedInteger}},et=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=tt(e,s),a=i in Ze,r=a?Ze[i].type:Ke.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))+tt(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}},tt=(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},st=(t,s)=>{switch(s){case Ke.SignedInteger:return t.getInt8(0);case Ke.UnsignedInteger:return tt(t);case Ke.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Ke.String:return new TextDecoder('ascii').decode(t);case Ke.UTF8:return new TextDecoder('utf-8').decode(t);case Ke.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Ke.Master:case Ke.Binary:return t;default:e.assertNever(s)}},it=(e,t)=>{let s=0;for(;s<e.byteLength;){const i=new DataView(e.buffer,e.byteOffset+s),a=et(i);if(!t(a))return;a.type===Ke.Master&&it(a.value,t),s=a.value.byteOffset-e.byteOffset+a.valueSize}},at=[Xe.Info,Xe.SeekHead,Xe.Tracks,Xe.Chapters,Xe.Cluster,Xe.Cues,Xe.Attachments,Xe.Tags],rt=[Xe.Timestamp,Xe.SilentTracks,Xe.SilentTrackNumber,Xe.Position,Xe.PrevSize,Xe.SimpleBlock,Xe.BlockGroup,Xe.EncryptedBlock],ot={validateData:e=>{if(e.getUint32(0)!==Xe.EBML)return!1;let t,s,i;const a=et(e);return it(a.value,(({tag:e,type:a,value:r})=>(e===Xe.EBMLReadVersion?t=st(r,a):e===Xe.DocType?s=st(r,a):e===Xe.DocTypeReadVersion&&(i=st(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 it(t,(({tag:e,type:t,value:c,valueSize:l})=>{if(e===Xe.SeekID){const e=st(c,t);n=tt(e)}else e!==Xe.SeekPosition&&(n=void 0);return e===Xe.Segment?(s=c.byteOffset,i=c.byteOffset+l):e===Xe.Info?d=!0:e===Xe.SeekHead?u=!0:e===Xe.TimestampScale?a=st(c,t):e===Xe.Duration?r=st(c,t):e===Xe.SeekPosition&&n===Xe.Cues?o=st(c,t):d&&u&&at.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 it(t,(({tag:e,type:t,value:s})=>{switch(e){case Xe.Cues:i=!0;break;case Xe.CuePoint:n&&r(n)&&o.push(n),n={};break;case Xe.CueTime:n&&(n.time=st(s,t));break;case Xe.CueTrackPositions:break;case Xe.CueClusterPosition:n&&(n.position=st(s,t));break;default:i&&at.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:Me.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{it(e,(i=>i.tag===Xe.Cluster?i.tagSize<=e.byteLength?(t=i.tagSize,!1):(t+=i.tagHeaderSize,!0):!!rt.includes(i.tag)&&(t+i.tagSize<=e.byteLength&&(t+=i.tagSize,s||=[Xe.SimpleBlock,Xe.BlockGroup,Xe.EncryptedBlock].includes(i.tag)),!0)))}catch(e){}return t>0&&t<=e.byteLength&&s?new DataView(e.buffer,e.byteOffset,t):null}};class nt{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;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new C;destroyAbortController=new C;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;constructor(t,s,i,a,{fetcher:r,tuning:o,getCurrentPosition:n}){switch(this.fetcher=r,this.tuning=o,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.container=i,i){case Ve.MP4:this.containerParser=Je;break;case Ve.WEBM:this.containerParser=ot;break;default:e.assertNever(i)}this.initData=new Map(a.map((e=>[e.id,null]))),this.segments=new Map,this.representations=new Map(a.map((e=>[e.id,e]))),this.kind=t,this.mediaSource=s,this.sourceBuffer=null}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 je(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((()=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((e=>this.pruneBuffer(e)))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((e=>this.error$.next(e)))),yield this.loadInit(s,'high',!0);const i=this.initData.get(s.id),a=this.segments.get(s.id);if(e.assertNonNullable(i,'No init buffer for starting representation'),e.assertNonNullable(a,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let r=0;for(const e of a)e.time.from-r>=300&&this.gaps.push({representation:s.id,from:r,to:e.time.from}),r=e.time.to;e.isNonNullable(s.duration)&&s.duration-r>=300&&this.gaps.push({representation:s.id,from:r,to:s.duration}),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=e.abortable(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;this.switchingToRepresentationId=t;const s=this.representations.get(t);e.assertNonNullable(s,`No such representation ${t}`);let i=this.initData.get(t);if(e.isNullable(i)?yield this.loadInit(s,'high',!1):i instanceof Promise&&(yield i),i=this.initData.get(t),!(i&&i instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal);const a=this.getCurrentPosition();e.isNonNullable(a)&&this.maintain(a)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new C,this.abortBuffer()}maintain(t){if(e.isNullable(this.downloadingRepresentationId)||e.isNullable(this.playingRepresentationId)||e.isNullable(this.sourceBuffer))return;const s=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(e.assertNonNullable(s,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,s=xe(this.sourceBuffer.buffered,t),i=a?a.time.to+e:-1/0;a&&s>=a.time.to-t+e&&(r=i)}let o=[];if(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);else if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,s.segmentReference.type,r),o.length)){let e='auto';if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))e='high';else{const t=o.at(0);t&&t.time.from-a.time.to>=this.forwardBufferTarget/2&&(e='low')}this.loadSegments(o,s,e)}!this.allInitsLoaded&&a&&a.status===Me.FED&&!o.length&&xe(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const n=i.at(-1);n&&n.status===Me.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===n))}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}setTarget(e){this.forwardBufferTarget=e}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex((({status:e,time:{from:t,to:i}})=>e===Me.NONE&&(t>s||t<=s&&i>=s)&&i<=s+this.forwardBufferTarget));if(-1===i)return[];if(t!==Oe.BYTE_RANGE)return e.slice(i,i+1);const a=e;let r=0;const o=[];for(let e=i;e<a.length&&r<=this.tuning.dash.segmentRequestSize;e++){const t=a[e];if(r+=t.byte.to+1-t.byte.from,t.status!==Me.NONE)break;o.push(t)}return o}async loadSegments(t,s,i='auto'){if(!t.length)return;let a,r,o=t;const{type:n}=s.segmentReference;switch(n){case Oe.BYTE_RANGE:a=s.segmentReference.url,r={from:t.at(0).byte.from,to:t.at(-1).byte.to};break;case Oe.TEMPLATE:{const e=t.at(0);a=new URL(e.url,s.segmentReference.baseUrl).toString(),o=[e];break}default:e.assertNever(n)}for(const e of o)e.status=Me.DOWNLOADING,this.activeSegments.add({segment:e,loadedBytes:0,fedBytes:0,representationId:s.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await e.abortable(d,async function*(){const t=e.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))(),d.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(a,{rangeMethod:Ge.PARAM,range:r,onProgress:(e,t)=>{if(!d.aborted)try{this.onSomeDataLoaded(e,s.id,r?r.from:0,t,d)}catch(e){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:e})}},signal:d,priority:i}).then((()=>this.failedDownloads=0),(e=>{for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.onSegmentDownloadError(e)}))}onSegmentDownloadError(t){let s=!1;const i=this.getCurrentPosition();if(this.sourceBuffer&&e.isNonNullable(i)){s=xe(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,s||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}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=Me.FED,'size'in e.segment&&(e.segment.size=e.fedBytes);for(const s of this.representations.values())if(s.id!==t)for(const t of this.segments.get(s.id)??[])t.status===Me.FED&&t.time.from===e.segment.time.from&&t.time.to===e.segment.time.to&&(t.status=Me.NONE);this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])},n=this.representations.get(t);if(!n)return;const d=n.segmentReference.type,u=e.byteLength;for(const n of this.activeSegments){const{segment:h}=n,c=d===Oe.BYTE_RANGE,l=c?h.byte.to-h.byte.from+1:u;if(n.representationId!==t)continue;if(!(!c||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){r(n);continue}const p=c?h.byte.from-s:0,m=p<i,S=(c?h.byte.to-s:e.byteLength)<=i;if(h.status===Me.DOWNLOADING&&m&&S){h.status=Me.DOWNLOADED,this.activeSegments.delete(n);const t=new DataView(e.buffer,e.byteOffset+p,l);this.sourceBufferTaskQueue.append(t,a).then((e=>e&&!a.aborted?o(n):r(n)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(n.loadedBytes=Math.min(l,i-p),n.loadedBytes>n.fedBytes)){const t=new DataView(e.buffer,e.byteOffset+p+n.fedBytes,n.loadedBytes-n.fedBytes),s=n.loadedBytes===l?t:this.containerParser.parseFeedableSegmentChunk(t);s?.byteLength&&(h.status=Me.PARTIALLY_FED,n.fedBytes+=s.byteLength,this.sourceBufferTaskQueue.append(s,a).then((e=>{!e||a.aborted?r(n):n.fedBytes===l&&o(n)})))}}}abortSegment(e){e.status===Me.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then((()=>e.status=Me.NONE)),e.status=Me.NONE):e.status=Me.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,i]of this.initData.entries()){const a=i instanceof Promise;t||=a,null===i&&(e=s)}if(!e)return void(this.allInitsLoaded=!0);if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Fe((()=>this.loadInit(s,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,s='auto',i=!1){const a=this.tuning.dash.useFetchPriorityHints?s:'auto',r=(!i&&this.failedDownloads>0?e.abortable(this.destroyAbortController.signal,async function*(){const t=e.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a))).then((e=>{if(!e)return;const{dataView:s,segments:i}=e,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(t.id,a),this.segments.set(t.id,i)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,r),r}async pruneBuffer(t){const 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;const d=e=>{r=Math.min(r,e.time.from),o=Math.max(o,e.time.to);const t='size'in e?e.size??0:e.byte.to-e.byte.from;a+=t};for(const e of i){if(e.time.to>=s||a>=t)break;e.status===Me.FED&&d(e)}if(n=isFinite(r)&&isFinite(o),!n){a=0,r=1/0,o=-1/0;for(const e of i){if(e.time.from<s+this.forwardBufferTarget||a>t)break;e.status===Me.FED&&d(e)}}return n=isFinite(r)&&isFinite(o),!!n&&this.sourceBufferTaskQueue.remove(r/1e3,o/1e3)}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fe((()=>{try{this.detectGaps(e,t)}catch(e){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:e})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(e.isNullable(this.sourceBuffer)||e.isNullable(this.playingRepresentationId))return;const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const s=1e3*this.sourceBuffer.buffered.start(e),i=1e3*this.sourceBuffer.buffered.end(e);t.push({from:s,to:i})}const s=this.tuning.dash.segmentTimelineTolerance;for(const e of this.segments.values())for(const i of e){const e=t.some((e=>e.from-s<=i.time.from&&e.to+s>=i.time.to));i.status!==Me.FED||e||(i.status=Me.NONE)}}}const dt=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*60*1e3+60*t(s?.[6],i)*60*1e3+60*t(s?.[7],i)*1e3+1e3*t(s?.[8],i)},ut=(t,s)=>{let i=t;i=i.replaceAll('$$','$');const a={RepresentationID:s.representationId,Number:s.segmentNumber,Bandwidth:s.bandwidth,Time:s.segmentTime};for(const[t,s]of Object.entries(a)){const a=new RegExp(`\\$${t}(?:%0(\\d+)d)?\\$`,'g');i=i.replaceAll(a,((t,i)=>e.isNullable(s)?t:e.isNullable(i)?s:s.padStart(parseInt(i,10),'0')))}return i},ht=['timeupdate','progress','play','seeked','stalled'];var ct,lt;!function(e){e.NONE='none',e.MANIFEST_LOADED='manifest_loaded',e.REPRESENTATION_SELECTED='representation_selected'}(ct||(ct={}));class pt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new e.Subscription;fetcher;state$=new k(ct.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 C;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ye({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=e.abortable(this.destroyController.signal,async function*(t,s){this.element=t,this.state$.startTransitionTo(ct.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(s).catch((e=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:e})));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=dt(d);else if(u){const t=dt(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');if('text'!==r)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?Z(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(),w=[...c,...o,...m];let $;const P=u.querySelector('SegmentBase'),A=u.querySelector('SegmentTemplate');if(P){const e=u.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[t,s]=e.split('-').map((e=>parseInt(e,10))),i={from:t,to:s},a=u.querySelector('SegmentBase')?.getAttribute('indexRange'),[r,o]=a?a.split('-').map((e=>parseInt(e,10))):[],n=a?{from:r,to:o}:void 0;$={type:Oe.BYTE_RANGE,url:k,initRange:i,indexRange:n}}else{if(!A)throw new ReferenceError('Unknown MPD segment referencing type');{const e={representationId:u.getAttribute('id')??void 0,bandwidth:u.getAttribute('bandwidth')??void 0},t=parseInt(A.getAttribute('timescale')??'',10),s=A.getAttribute('initialization')??'',i=A.getAttribute('media'),a=parseInt(A.getAttribute('startNumber')??'',10)??1,r=ut(s,e);if(!i)throw new ReferenceError('No media attribute in SegmentTemplate');const o=A.querySelectorAll('SegmentTimeline S')??[],n=[];let d=a,h=0;for(const s of o){const a=1e3*parseInt(s.getAttribute('d')??'',10),r=parseInt(s.getAttribute('r')??'',10)||0,o=parseInt(s.getAttribute('t')??'',10)??void 0;for(let s=0;s<r+1;s++){const s=ut(i,{...e,segmentNumber:d.toString(10),segmentTime:o.toString(10)}),r=o?o/t:h;h+=a/t;const u=h;d++,n.push({time:{from:r,to:u},url:s})}}$={type:Oe.TEMPLATE,baseUrl:k,initUrl:r,segments:n}}}if(!p||!d)continue;const x={video:Le.VIDEO,audio:Le.AUDIO,text:Le.TEXT}[p];x&&i[x].push({id:T,kind:x,segmentReference:$,profiles:w,duration:n,bitrate:b,mime:d,codecs:l,width:S,height:f,fps:y,quality:v})}}return{duration:n,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(ct.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(ct.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new nt(Le.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],e.isNonNullable(s)&&(this.audioBufferManager=new nt(Le.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=e.merge(...this.bufferManagers.map((e=>e.fullyBuffered$))).pipe(e.map((()=>this.bufferManagers.every((e=>e.fullyBuffered$.getValue()))))),r=e.merge(...this.bufferManagers.map((e=>e.onLastSegment$))).pipe(e.map((()=>this.bufferManagers.some((e=>e.onLastSegment$.getValue())))));this.subscription.add(e.merge(this.forceEnded$,e.combine({allBuffersFull:a,someBufferEnded:r}).pipe(e.filter((({allBuffersFull:e,someBufferEnded:t})=>e&&t)))).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.bufferManagers.map((e=>e.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)))),e.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&e.isNonNullable(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ct.REPRESENTATION_SELECTED),e.assertNonNullable(this.element),this.subscription.add(e.merge(...ht.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((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&Ue(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this));async switchRepresentation(e,t){return{[Le.VIDEO]:this.videoBufferManager,[Le.AUDIO]:this.audioBufferManager,[Le.TEXT]:null}[e]?.switchTo(t)}seek(t,s){let i;e.assertNonNullable(this.element),e.assertNonNullable(this.videoBufferManager),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),Ue(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ct.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager?.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager?.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=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)return;const e=1e3*this.element.currentTime,t=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const s of this.bufferManagers)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'}(lt||(lt={}));const mt=({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}},St=(e,t,s)=>{const i=t.indexOf(s);return e.at(Math.round(e.length*i/t.length))??e.at(-1)};class ft{subscription=new e.Subscription;videoState=new k(lt.STOPPED);video;player;params;elementSize$=new e.ValueSubject(void 0);textTracksManager=new Q;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new oe;constructor(e){this.params=e,this.video=z(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 pt({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=K(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.playing$,t.firstFrameEvent$),r(i.canplay$,t.canplay$),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(),e.mapTo(void 0)),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)),this.subscription.add(G(this.video,s.playbackRate,i.playbackRateState$,a)),r(ue(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(lt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(lt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===lt.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(e.filter((({to:e})=>e===ct.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(lt.READY)})));const o=e=>t.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:e});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 i=this.player.state$.getState(),a=this.player.state$.getTransition();if(i===ct.NONE||!this.videoTracks.length)return;const r=i===ct.MANIFEST_LOADED&&!a,n=i===ct.REPRESENTATION_SELECTED&&!a,d=s.autoVideoTrackSwitching.getState(),u=s.videoTrack.getState(),h=this.videoTracks.find((({track:{id:e}})=>e===u))?.track,c=t.currentVideoTrack$.getValue(),l=xe(this.video.buffered,1e3*this.video.currentTime),p=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(l/Math.min(p,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),S=Math.max(h&&!d?this.audioRepresentations.get(h.id)?.bitrate??0:0,c?this.audioRepresentations.get(c.id)?.bitrate??0:0),f=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(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),b=d?f??h:h??f;if(s.autoVideoTrackSwitching.getTransition()&&(s.autoVideoTrackSwitching.setState(d),this.player.setBufferTarget(p)),r){const t=b&&this.videoTracks.find((({track:e})=>e===b))?.representation;e.assertNonNullable(t),this.player.initRepresentations(t.id,this.audioRepresentations.get(t.id)?.id)}else if(n){const e=b&&this.videoTracks.find((({track:e})=>e===b))?.representation;if(e){const t=this.audioRepresentations.get(e.id);this.player.switchRepresentation(Le.VIDEO,e.id).catch(o),t&&this.player.switchRepresentation(Le.AUDIO,t.id).catch(o)}}}),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 n=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,a))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort(((e,t)=>t.bitrate-e.bitrate)),s=Array.from(e.representations.video).sort(((e,t)=>t.bitrate-e.bitrate));for(const e of s){const i=mt(e);if(i){this.videoTracks.push({track:i,representation:e});const a=St(t,s,e);a&&this.audioRepresentations.set(e.id,a)}}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!==lt.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),s!==exports.PlaybackState.STOPPED){if(t===lt.STOPPED)return this.videoState.startTransitionTo(lt.READY),void this.prepare();switch(t){case lt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(lt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(lt.PLAYING),this.playIfAllowed()));case lt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(lt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case lt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(lt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==lt.STOPPED&&(this.videoState.startTransitionTo(lt.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(lt.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(lt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const bt={};var gt;!function(e){e.INITIALIZING='initializing',e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(gt||(gt={}));const vt=(t,s)=>new e.Observable((e=>{const i=(t,s)=>e.next(s);return t.on(s,i),()=>t.off(s,i)}));class yt{subscription=new e.Subscription;videoState=new k(gt.INITIALIZING);video;params;hls;textTracksManager=new Q;trackLevels=new Map;constructor(e){this.video=z(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||(bt.Hls=t.default,bt.Events=t.default.Events,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(bt.Hls,'hls.js not loaded'),this.hls=new bt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(gt.STOPPED)}subscribe(){e.assertNonNullable(bt.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=K(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.loadStart$,s.firstBytesEvent$),r(a.playing$,s.firstFrameEvent$),r(a.canplay$,s.canplay$),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(G(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(vt(this.hls,bt.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(gt.PLAYING),f(t.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(gt.PAUSED),f(t.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)),r(vt(this.hls,bt.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(vt(this.hls,bt.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=vt(this.hls,bt.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!==gt.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===h.Requested&&this.seek(a.position),s){case exports.PlaybackState.STOPPED:switch(t){case gt.STOPPED:break;case gt.READY:case gt.PLAYING:case gt.PAUSED:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case gt.PLAYING:break;case gt.STOPPED:this.prepare();break;case gt.READY:case gt.PAUSED:this.playIfAllowed();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case gt.PAUSED:break;case gt.STOPPED:this.prepare();break;case gt.READY:this.videoState.setState(gt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case gt.PLAYING:this.pause();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};prepare(){this.videoState.startTransitionTo(gt.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(gt.PLAYING);await Se(this.video)||(this.videoState.setState(gt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(gt.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(gt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}var Tt=async e=>{const t=await _(e,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0};const Et=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},kt=async(e,t=e)=>{const s=await _(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=Et(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 wt,$t,Pt;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}(wt||(wt={}));class At{subscription=new e.Subscription;videoState=new k(wt.STOPPED);video;params;textTracksManager=new Q;manifests$=new e.ValueSubject([]);maxSeekBackTime$;liveOffset=new W;manifestStartTime$=new e.ValueSubject(void 0);constructor(t){this.params=t,this.video=z(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]),kt(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=K(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.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),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.subscription.add(G(this.video,s.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(wt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(wt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===wt.READY&&this.videoState.setState(wt.READY),this.videoState.getState()===wt.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===wt.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(),Tt(s).then((t=>{if(e.isNullable(t)){const t=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(e.isNullable(t)||!isFinite(t))try{_(s).then((e=>e.text())).then((t=>{const i=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(t)?.[1];if(i){const t=new URL(i,s).toString();Tt(t).then((t=>{e.isNullable(t)||this.maxSeekBackTime$.next(t)}))}}))}catch(e){}}else this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(wt.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!==wt.STOPPED&&(this.videoState.startTransitionTo(wt.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(wt.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===wt.STOPPED)return this.videoState.startTransitionTo(wt.READY),void this.prepare();if(a||r){const e=this.videoState.getState();return this.videoState.setState(wt.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(wt.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case wt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(wt.PAUSED),this.liveOffset.pause(),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(wt.PLAYING),this.playIfAllowed()));case wt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(wt.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case wt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(wt.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 wt.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'}($t||($t={}));class xt{subscription=new e.Subscription;videoState=new k($t.STOPPED);video;params;textTracksManager=new Q;manifests$=new e.ValueSubject([]);constructor(e){this.params=e,this.video=z(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)),kt(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=K(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.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),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(G(this.video,s.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState($t.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState($t.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===$t.READY&&this.videoState.setState($t.READY),this.videoState.getState()===$t.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===$t.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($t.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!==$t.STOPPED&&(this.videoState.startTransitionTo($t.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($t.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===$t.STOPPED)return this.videoState.startTransitionTo($t.READY),void this.prepare();if(a||r){const e=this.videoState.getState();this.videoState.setState($t.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 $t.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState($t.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($t.PLAYING),this.playIfAllowed()));case $t.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo($t.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case $t.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo($t.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case $t.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Pt||(Pt={}));class Nt{subscription=new e.Subscription;videoState=new k(Pt.STOPPED);video;trackUrls={};params;textTracksManager=new Q;constructor(e){this.params=e,this.video=z(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.params.desiredState.autoVideoTrackSwitching.setState(!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=K(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.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),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(G(this.video,s.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Pt.PLAYING),f(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Pt.PAUSED),f(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Pt.READY&&this.videoState.setState(Pt.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()===Pt.PLAYING&&this.playIfAllowed()}),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=U(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(Pt.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!==Pt.STOPPED&&(this.videoState.startTransitionTo(Pt.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(Pt.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===Pt.STOPPED)return this.videoState.startTransitionTo(Pt.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 Pt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Pt.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Pt.PLAYING),this.playIfAllowed()));case Pt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Pt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Pt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Pt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}const Rt=['stun:videostun.mycdn.me:80'],Dt=()=>null;class _t{options;ws=null;peerConnection=null;serverUrl='';streamKey='';stream=null;signalingType='JOIN';retryTimeout;retryCount=0;externalStartCallback=Dt;externalStopCallback=Dt;externalErrorCallback=Dt;constructor(e,t){this.options=this.normalizeOptions(t);const s=e.split('/');this.serverUrl=s.slice(0,s.length-1).join('/'),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(e){this.handleSystemError(e)}}onStop(e){try{this.externalStopCallback=e}catch(e){this.handleSystemError(e)}}onError(e){try{this.externalErrorCallback=e}catch(e){this.handleSystemError(e)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(e){this.handleRTCError(e)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(e){this.handleRTCError(e)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case'JOIN':case'CALL_JOIN':this.handleJoinMessage(t);break;case'UPDATE':this.handleUpdateMessage(t);break;case'STATUS':this.handleStatusMessage(t)}}catch(e){this.handleRTCError(e)}}handleJoinMessage(e){switch(e.inviteType){case'ANSWER':this.handleAnswer(e.sdp);break;case'CANDIDATE':this.handleCandidate(e.candidate)}}handleStatusMessage(e){switch(e.status){case'UNPUBLISHED':this.handleUnpublished()}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(e){this.handleRTCError(e)}}async handleLogin(){try{const e={iceServers:[{urls:Rt}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:e}))}catch(e){this.handleRTCError(e)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(e){this.handleRTCError(e)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:'CANDIDATE',candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;['failed','closed'].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}),t=e.sdp||'';if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(t))throw new Error('No h264 codec support error');return e}handleRTCError(e){try{this.externalErrorCallback(e||new Error('RTC connection error'))}catch(e){this.handleSystemError(e)}}handleNetworkError(){try{this.externalErrorCallback(new Error('Network error'))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(e){throw new Error('Can not parse socket message')}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),1e3)}normalizeOptions(e={}){const t={stunServerList:Rt,maxRetryNumber:3,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Ct;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(Ct||(Ct={}));class It{subscription;params;log;video;videoState=new k(Ct.STOPPED);liveStreamClient;maxSeekBackTime$=new e.ValueSubject(0);constructor(t){this.subscription=new e.Subscription,this.params=t,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=z(t.container),this.liveStreamClient=new _t(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'WebRTCLiveProvider',message:'WebRTCLiveProvider 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)}`})}));const a=K(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,t.liveTime$),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$),this.subscription.add(a.durationChange$.subscribe((e=>{t.duration$.next(e===1/0?0:e)}))).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Ct.READY&&this.videoState.setState(Ct.READY)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ct.PAUSED)}),i)).add(a.playing$.subscribe((()=>{this.videoState.setState(Ct.PLAYING)}),i)).add(a.error$.subscribe(t.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(j(this.video,s.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(t.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe((i=>{switch(i.to){case Ct.STOPPED:t.position$.next(0),t.duration$.next(0),s.playbackState.setState(exports.PlaybackState.STOPPED);break;case Ct.READY:break;case Ct.PAUSED:s.playbackState.setState(exports.PlaybackState.PAUSED);break;case Ct.PLAYING:s.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return e.assertNever(i.to)}}),i)).add(e.merge(s.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(s.isLooped.stateChangeStarted$.subscribe((()=>s.isLooped.setState(!1)),i)),this.subscription.add(s.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>s.autoVideoTrackSwitching.setState(!1)),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Ct.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',message:e.message,thrown:e})}playIfAllowed(){Se(this.video).then((e=>{e||(this.videoState.setState(Ct.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}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!==Ct.STOPPED&&(this.videoState.startTransitionTo(Ct.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ct.STOPPED),f(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(t===Ct.STOPPED)return this.videoState.startTransitionTo(Ct.READY),void this.prepare();if(a)this.prepare();else switch(t){case Ct.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Ct.PAUSED),f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ct.PLAYING),this.playIfAllowed()));case Ct.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ct.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&f(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ct.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ct.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&f(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}class Lt{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 Bt=qe(),Ot=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Mt=document.createElement('video'),Vt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Mt.canPlayType?.('application/x-mpegurl')||Mt.canPlayType?.('vnd.apple.mpegURL')),webrtc:Boolean(window.RTCPeerConnection)},Ut={mp4:Boolean(Mt.canPlayType?.('video/mp4')),webm:Boolean(Mt.canPlayType?.('video/webm'))},Ft={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"'))},qt=(Ft.h264||Ft.h265)&&Ft.aac,Ht=!Bt,jt=Vt.hls&&Ut.mp4&&(Ot||Bt),Gt=Boolean(window.WebSocket);const Yt=3e4,Qt=18e4,zt=3,Wt=100,Jt={cacheDuration:12e4},Xt={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Kt={maxPausedTime:3e4},Zt={maxPausedTime:3e4};class es{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,canplay$: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 Lt(((t,s=!1)=>t.filter((t=>{switch(t){case exports.VideoFormat.DASH:return Vt.mse&&Ut.mp4&&qt&&Ht;case exports.VideoFormat.DASH_SEP:return Vt.mse&&Ut.mp4&&qt;case exports.VideoFormat.DASH_WEBM:return Vt.mse&&Ut.webm&&Ft.vp9&&Ft.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return Vt.mse&&Ut.mp4&&qt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return jt||s&&Vt.mse&&Ut.mp4&&qt;case exports.VideoFormat.MPEG:return Ut.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Vt.webrtc&&Gt&&Ft.h264&&(Ut.mp4||Ut.webm);default:return e.assertNever(t)}})))(i.filter((s=>e.isNonNullable(t.sources[s]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Lt(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=1e3*this.providerOutput.position$.getValue(),s=this.params.desiredState.seekState.getState(),i=s.state!==h.None;this.params.desiredState.seekState.setState({state:h.Requested,position:i?s.position:t,forcePrecise:!!i&&s.forcePrecise}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.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,o={container:i,source:null,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case exports.VideoFormat.DASH:{const i=s[t];return e.assertNonNullable(i),new Ie({...o,source:i,config:Jt})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const i=s[t];return e.assertNonNullable(i),this.params.tuning.useDashJs?new pe({...o,source:i,format:t,config:Zt}):new ft({...o,source:i})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[t];return e.assertNonNullable(i),jt||!this.params.tuning.useHlsJs?new xt({...o,source:i}):new yt({...o,source:i})}case exports.VideoFormat.HLS_LIVE:{const i=s[t];return e.assertNonNullable(i),new At({...o,source:i,config:Kt})}case exports.VideoFormat.MPEG:{const i=s[t];return e.assertNonNullable(i),new Nt({...o,source:i})}case exports.VideoFormat.DASH_LIVE:{const i=s[t];return e.assertNonNullable(i),new Pe({...o,source:i,config:Xt})}case exports.VideoFormat.WEB_RTC_LIVE:{const o=s[t];return e.assertNonNullable(o),new It({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return 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 $({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:Yt,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(e.filter((({type:e})=>void 0!==e)))},new e.Observable((t=>{const s=new e.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(e.map((({from:e,to:t})=>`${e}-${t}`))),r=a.desiredPlaybackState$.stateChangeEnded$,o=a.providerChanged$,n=new e.Subject;let d=0,u='unknown';return s.add(i.subscribe((e=>{d&&window.clearTimeout(d),u=e,d=window.setTimeout((()=>n.next(e)),a.maxTransitionInterval)}))),s.add(r.subscribe((()=>{window.clearTimeout(d),u='provider change',d=0}))),s.add(o.subscribe((()=>{d&&(window.clearTimeout(d),d=window.setTimeout((()=>n.next(u)),a.maxTransitionInterval))}))),s.add(n.subscribe(t)),()=>{window.clearTimeout(d),s.unsubscribe()}}))).pipe(e.map((e=>({id:`ProviderHangup:${e}`,message:`A ${e} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),i.add(this.providerError$.pipe(e.throttle(Wt,{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]+Qt?(t=[],this.switchToNextProvider()):(t[s]=i,this.reinitProvider()),s=(s+1)%zt}))),i}}const ts=(e,t,s)=>s*t+(1-s)*e;class ss{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(t){this.params=t,this.pastMeasures=Array(t.deviationDepth),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 ae(`raw_${s}`),this.smoothedSeries$=new ae(`smoothed_${s}`),this.reportedSeries$=new ae(`reported_${s}`),this.rawSeries$.next(t.initial),this.smoothedSeries$.next(t.initial),this.reportedSeries$.next(t.initial)}next(t){let s=0,i=0;for(let e=0;e<this.pastMeasures.length;e++)void 0!==this.pastMeasures[e]&&(s+=(this.pastMeasures[e]-this.smoothed)**2,i++);s/=i;const a=Math.sqrt(s),r=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=t,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(t),this.slow=ts(this.slow,t,this.params.emaAlphaSlow),this.fast=ts(this.fast,t,this.params.emaAlphaFast);const n=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=n(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>r||this.smoothed<o||(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))}}var is;!function(e){e[e.LOCAL_STORAGE=0]='LOCAL_STORAGE',e[e.SESSION_STORAGE=1]='SESSION_STORAGE',e[e.RUNTIME=2]='RUNTIME'}(is||(is={}));const as=new Map;let rs=is.RUNTIME;const os=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(os,'test'),localStorage.removeItem(os),rs=is.LOCAL_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;try{sessionStorage.getItem(os),rs=is.SESSION_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;rs=is.RUNTIME}}})();const ns=(t,s)=>{switch(rs){case is.LOCAL_STORAGE:try{localStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case is.SESSION_STORAGE:try{sessionStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case is.RUNTIME:return void as.set(t,s);default:e.assertNever(rs)}},ds=window.navigator.connection,us=()=>{const t=ds?.downlink;if(e.isNonNullable(t)&&10!==t)return 1e3*t},hs=()=>{const t=ds?.rtt;if(e.isNonNullable(t)&&3e3!==t)return t},cs=(e,t,s)=>{const i=8*s;return i/(i/e+t)};class ls{throughput;rtt;subscription=new e.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(t){this.tuningConfig=t;const s=ls.load('one_video_throughput')||(t.useBrowserEstimation?us():void 0)||5e3,i=ls.load('one_video_rtt')??(t.useBrowserEstimation?hs():void 0)??0;if(this.throughput$=new e.ValueSubject(s),this.rtt$=new e.ValueSubject(i),this.rttAdjustedThroughput$=new e.ValueSubject(cs(s,i,t.rttPenaltyRequestSize)),this.throughput=new ss({initial:s,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:-1,deviationDepth:t.deviationDepth,deviationFactor:t.deviationFactor,label:'throughput'}),this.rtt=new ss({initial:i,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:1,deviationDepth:t.deviationDepth,deviationFactor:t.deviationFactor,label:'rtt'}),t.useBrowserEstimation){const t=()=>{const t=us();t&&this.throughput.next(t);const s=hs();e.isNonNullable(s)&&this.rtt.next(s)};ds&&'onchange'in ds&&this.subscription.add(e.fromEvent(ds,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((e=>{ns('one_video_throughput',e.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((e=>{ns('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})=>cs(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.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(t){let s=0,i=e.now();const a=new e.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(t),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,1)}this.concurrentDownloads.delete(t),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=>{this.concurrentDownloads.delete(t),s.releaseLock(),t.cancel(`Throughput Estimator error: ${e}`).catch((()=>{}))},d=async({done:u,value:h})=>{u?(this.addRawSpeed(i,e.now()-a,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,r+=h.byteLength,r>=this.tuningConfig.streamMinSampleSize&&e.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,e.now()-o,this.concurrentDownloads.size),r=0,o=e.now()),await(s?.read().then(d,n)))};this.concurrentDownloads.add(t),s?.read().then(d,n)}addRawSpeed(e,t,s=1){if(ls.sanityCheck(e,t)){const i=8*e/t;this.throughput.next(i*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(rs){case is.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case is.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case is.RUNTIME:return as.get(t);default:e.assertNever(rs)}})(t);if(e.isNonNullable(s))return parseInt(s,10)??void 0}}const ps={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}};const ms=({playbackState:t,seekState:s,playbackAbort$:i,looped$:a,position$:r})=>new e.Observable((o=>{let n;const d=t.transitionEnded$.pipe(e.filter((e=>(e.from===exports.PlaybackState.PAUSED||e.from===exports.PlaybackState.STOPPED)&&e.to===exports.PlaybackState.PLAYING))),u=t.stateChangeEnded$.pipe(e.filter((e=>e.from===exports.PlaybackState.PLAYING&&e.to===exports.PlaybackState.PAUSED))),c=s.stateChangeEnded$.pipe(e.filter((({to:e})=>e.state===h.Requested&&(t.getTransition()?.from??t.getState())===exports.PlaybackState.PLAYING))),l=s.stateChangeEnded$.pipe(e.filter((({from:e,to:s})=>e.state===h.Applying&&s.state===h.None&&(t.getTransition()?.from??t.getState())===exports.PlaybackState.PLAYING))),p=e.merge(d,l).pipe(e.map((()=>r.getValue())),e.filter(e.isNonNullable)),m=e.merge(e.merge(u,c,i),a).pipe(e.map((()=>r.getValue())),e.filter(e.isNonNullable));return(new e.Subscription).add(p.subscribe((e=>{n=e}))).add(m.subscribe((t=>{if(e.isNullable(n)||n===t)return;const s={from:n,to:t};n=void 0,o.next(s)})))})),Ss={[o.SCREEN]:{vod:[...jt?[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:[],exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,...jt?[]:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND],exports.VideoFormat.MPEG],live:jt?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return 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;initedAt;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),playbackRate: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({}),currentPlaybackRate$:new e.ValueSubject(1),currentBuffer$:new e.ValueSubject({start:0,end: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={inited$:new e.Subject,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,canplay$:new e.Subject,log$:new e.Subject};experimental={element$:new e.ValueSubject(void 0),enableDebugTelemetry$:new e.ValueSubject(!1),dumpTelemetry:se};constructor(e={}){if(this.initLogs(),this.tuning=(e=>{const t={};for(const s of Object.keys(ps)){const i=ps[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 ls(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 es({screenFormatsPriority:[...Ss[o.SCREEN].live,...Ss[o.SCREEN].vod],chromecastFormatsPriority:[...Ss[o.CHROMECAST].live,...Ss[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,!1),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}setPlaybackRate(t){e.assertNonNullable(this.providerContainer);const s=this.providerContainer?.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(t),s.playbackRate=t),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.playbackRate.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.currentPlaybackRate$)).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)),e.filter((()=>!this.isPlaybackStarted))).subscribe((()=>{this.initedAt=e.now(),this.events.inited$.next(),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$.pipe(e.map((e=>e?{start:e.from,end:e.to}:{start:0,end:0}))).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$.pipe(e.once(),e.map((()=>e.now()-this.initedAt))).subscribe(this.events.firstBytes$)).add(t.providerOutput.firstFrameEvent$.pipe(e.once(),e.map((()=>e.now()-this.initedAt))).subscribe(this.events.firstFrame$)).add(t.providerOutput.canplay$.pipe(e.once(),e.map((()=>e.now()-this.initedAt))).subscribe(this.events.canplay$)).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:{const t=new e.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe((e=>t.next(e&&Math.floor(e/1e3))))),o.add(ms({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:t}).pipe(e.map((({from:e,to:t})=>({start:e,end:t})))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(ms({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).pipe(e.map((({from:e,to:t})=>({start:e,end:t})))).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(),playbackRate:this.info.currentPlaybackRate$.getValue(),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),te={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((e=>{ee=e})),this.providerContainer.current$.subscribe((({type:e})=>ie('provider',e))),t.duration$.subscribe((e=>ie('duration',e))),t.availableVideoTracks$.pipe(e.filter((e=>!!e.length)),e.once()).subscribe((e=>ie('tracks',e))),this.events.fatalError$.subscribe(new ae('fatalError')),this.events.managedError$.subscribe(new ae('managedError')),t.position$.subscribe(new ae('position')),t.currentVideoTrack$.pipe(e.map((e=>e?.quality))).subscribe(new ae('quality')),this.info.currentBuffer$.subscribe(new ae('buffer')),t.isBuffering$.subscribe(new ae('isBuffering'))].forEach((e=>this.subscription.add(e))),ie('codecs',Object.keys(Ft).filter((e=>Ft[e])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.74';
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.js'));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',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_ONDEMAND_VK='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS',r.HLS_LIVE='HLS_LIVE',r.WEB_RTC_LIVE='WEB_RTC_LIVE',function(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;const i=e.isNonNullable(window.chrome?.cast),a=Boolean(window.__onGCastApiAvailable);var r;i?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{delete window.__onGCastApiAvailable,e&&this.initializeCastApi()},a||(r='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',r),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,f=(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},S=(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 w;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(w||(w={}));class ${subscription=new e.Subscription;loadMediaTimeoutSubscription=new e.Subscription;videoState=new k(w.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_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return 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(),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default: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(w.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(w.PLAYING),S(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!==w.PAUSED&&e!==w.PLAYING||(this.videoState.setState(w.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();this.videoState.getTransition()?.to!==w.PLAYING&&e!==w.PAUSED||(this.videoState.setState(w.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===w.READY&&this.videoState.setState(w.READY)}handleRemoteStop(){this.videoState.getState()!==w.STOPPED&&this.videoState.setState(w.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_ONDEMAND: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=f(o.url),a='application/x-mpegurl',r=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const e='Unsupported format for Chromecast',t=new Error(e);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:e,thrown:t}),t}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');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===w.STOPPED)switch(i){case exports.PlaybackState.PLAYING:switch(t){case w.PLAYING:break;case w.PAUSED:case w.READY:this.videoState.startTransitionTo(w.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case w.PLAYING:this.videoState.startTransitionTo(w.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case w.PAUSED:break;case w.READY:this.videoState.startTransitionTo(w.PAUSED),this.videoState.setState(w.PAUSED);break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:e.assertNever(t)}break;default:e.assertNever(i)}else this.seek(r.position)}else t!==w.STOPPED&&(this.videoState.startTransitionTo(w.STOPPED),this.stop())}}class P{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 P{constructor(){super(),this.listeners||P.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 R=N({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),D=R?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;R?D.Request:window.Request;const C=R?x:window.AbortController,I=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]=I(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(I),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 C,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 _(o,{signal:d}).then((e=>{if(u.response=e,!e.ok||!e.body)return void this.onBigRequestError(u);const[t,s]=e.body.tee();this.params.onDownloadStream?.(s);const r=t.getReader(),o=parseInt(e.headers.get('Content-Length')??'',10)||a-i+1;u.data=new ArrayBuffer(o);const n=new Uint8Array(u.data),d=async({done:e,value:t})=>{e?this.onBigRequestProgress(u):t&&(n.set(t,u.loaded),u.loaded+=t.byteLength,this.onBigRequestProgress(u),await(r?.read().then(d,L.suppressStreamErrors).catch(h)))};r?.read().then(d,L.suppressStreamErrors).catch(h)}),L.suppressAbort).catch((e=>this.onBigRequestError(u,e))),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a,response:r}){if(!this.activeRequests.has(e)||!a)return;const o=this.dashJsRequestQueue.get(e)??[];for(const n of o){const{request:o}=n,[d,u]=I(o),h=d>=t&&u<=t+i,c=t>=d&&t+i<u,l=a.slice(d-t,Math.min(u-t+1,i));if((h||c)&&(o.requestStartDate=o.requestStartDate??new Date,o.firstByteDate=o.firstByteDate??new Date,o.bytesLoaded=l.byteLength,o.bytesTotal=s-t),h){o.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter((e=>e!==n))),n.success?.(l,'',e);const t=r?Array.from(r.headers.entries()).map((([e,t])=>`${e}: ${t}`)).join('\r\n'):'';this.dashMetrics?.addHttpRequest(o,e,r?.status??200,t,[])}else c&&n.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]=I(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]=I(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 M=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)},V=t=>{const s=new e.ValueSubject(1/0),i=new e.Subject,a=new e.ValueSubject(void 0),r=new e.ValueSubject(void 0);let o=NaN,n=!1;return t.extend('XHRLoader',(function(){const{parent:t}=this,d=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const d=t.onload,u=t.progress;t.onload=function(...t){return(t=>{const i=Object.fromEntries(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((e=>e.split(': '))));if('x-playback-duration'in i||'x-playback-duration-millis'in i){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)}const o=i['x-delivery-type']??exports.HttpConnectionType.HTTP1,n={1:!0,0:!1}[i['x-reused']]??void 0;a.next(o),r.next(n)})(this),d(...t)},t.progress=function(...e){return this.readyState>=2&&!n&&(n=!0,i.next(Date.now()-o)),u(...e)},o=Date.now(),n=!1}return d(t)}}}),!0),{playbackDuration$:s,ping$:i,connectionReused$:r,connectionType$:a}},U=e=>{const t=new URL(e);return t.searchParams.set('quic','1'),t.toString()},F=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=(t,s,i,a)=>q(s,(()=>t.playbackRate),(s=>{e.isNonNullable(s)&&(t.playbackRate=s)}),{changed$:i,onError:a}),Y=(e,t)=>{if(e.id===t)return!0;const[s,i,a]=t.split('|');return e.language===i&&e.label===a};class Q{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(Q.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)&&Y(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 z=e=>{const t=document.createElement('video');return t.setAttribute('crossorigin','anonymous'),t.setAttribute('playsinline','playsinline'),e.appendChild(t),t};class W{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}}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({from:s,to:i,i:t})}return this._buffer.sort((function(e,t){return e.from-t.from})),this._buffer}getByTime(e){return this._buffer.find((t=>e>=t.from&&e<t.to))}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(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((({from:i,to: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 X=(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{from:i,to: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{from:i,to:a}};const K=t=>{const s=s=>e.fromEvent(t,s).pipe(e.mapTo(void 0));['canplaythrough','playing','pause','canplay','seeked','seeking','loadstart','loadedmetadata','loadeddata','durationchange'].map((e=>t.addEventListener(e,(t=>{console.log('HTMLVideoElement',e,t)}))));const i=e.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((s=>e.fromEvent(t,s)))).pipe(e.map((e=>'ended'===e.type?t.readyState<2:t.readyState<3)),e.filterChanged()),a=e.merge(e.fromEvent(t,'progress'),e.fromEvent(t,'timeupdate')).pipe(e.map((()=>X(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,'ratechange').pipe(e.map((()=>t.playbackRate))),n=e.fromEvent(t,'error').pipe(e.filter((e=>{const s=Boolean(t.error);return console.log('HTMLVideoElement error','ignoring:',!s,{errorField:t.error,readyState:t.readyState,event:e,src:t.src}),console.trace(),s})),e.map((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element',thrown:t.error??void 0}}))),d=e.fromEvent(t,'timeupdate').pipe(e.map((()=>t.currentTime))),u=new e.Subject;let h;return d.subscribe((s=>{t.loop&&e.isNonNullable(h)&&e.isNonNullable(s)&&h>=t.duration-.3&&s<=.3&&u.next(h),h=s})),{playing$:s('playing'),pause$:s('pause').pipe(e.filter((()=>!t.error))),canplay$:s('canplay'),ended$:s('ended'),looped$:u,error$:n,seeked$:s('seeked'),seeking$:s('seeking'),progress$:s('progress'),loadStart$:s('loadstart'),loadedMetadata$:s('loadedmetadata'),loadedData$:s('loadeddata'),timeUpdate$:d,durationChange$:e.fromEvent(t,'durationchange').pipe(e.map((()=>t.duration))),isBuffering$:i,currentBuffer$:a,volumeState$:r,playbackRateState$:o}},Z=e=>{if(e.includes('/')){const t=e.split('/');return parseInt(t[0])/parseInt(t[1])}return parseFloat(e)};let ee=!1,te={};const se=e=>{e(te)},ie=(e,t)=>{ee&&(te.meta=te.meta??{},te.meta[e]=t)};class ae{name;constructor(e){this.name=e}next(e){if(!ee)return;te.series=te.series??{};const t=te.series[this.name]??[];t.push([Date.now(),e]),te.series[this.name]=t}}const re=new ae('best_bitrate');class oe{last;history={};recordSelection(t){this.history[t.id]=e.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ne=(t,{container:s,throughput:i,tuning:a,limits:r,reserve:o=0,forwardBufferHealth:n,playbackRate:d,current:u,history:h})=>{const c=a.usePixelRatio?window.devicePixelRatio??1:1,l=a.limitByContainer&&s&&s.width>0&&s.height>0&&{width:s.width*c*a.containerSizeFactor,height:s.height*c*a.containerSizeFactor},p=l&&T(l),m=a.considerPlaybackRate&&e.isNonNullable(d)?d:1,f=t.filter((e=>!E(e.quality))).sort(((e,t)=>g(e.quality,t.quality)?-1:1)),S=f.at(-1)?.quality,y=f.at(0)?.quality,k=e.isNullable(r)||e.isNonNullable(r.min)&&e.isNonNullable(r.max)&&v(r.max,r.min)||e.isNonNullable(r.min)&&y&&g(r.min,y)||e.isNonNullable(r.max)&&S&&v(r.max,S),w=m*($=n??.5,P=a.bitrateFactorAtEmptyBuffer,A=a.bitrateFactorAtFullBuffer,(P-A)*Math.pow(2,-10*$)+A);var $,P,A;const x=f.filter((t=>{const s=!p||v(t.quality,p),d=!(e.isNonNullable(i)&&isFinite(i)&&e.isNonNullable(t.bitrate))||i-o>=t.bitrate*w,h=a.lazyQualitySwitch&&e.isNonNullable(a.minBufferToSwitchUp)&&u&&!E(u.quality)&&(n??0)<a.minBufferToSwitchUp&&g(t.quality,u.quality),c=k||(e.isNullable(r.max)||(l=t.quality,m=r.max,b[l].height<=b[m].height))&&(e.isNullable(r.min)||((e,t)=>b[e].height>=b[t].height)(t.quality,r.min));var l,m;return s&&d&&!h&&c}))[0];x&&x.bitrate&&re.next(x.bitrate);const N=x??f[Math.ceil((f.length-1)/2)]??t[0],R=N&&h&&h.history[N.id]&&e.now()-h.history[N.id]<=a.trackCooldown&&(!h.last||N.id!==h.last.id);if(N?.id&&h&&!R&&h.recordSelection(N),R&&h?.last){const e=h.last;return h?.recordSwitch(e),e}return h?.recordSwitch(N),N};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 Q;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 W;destroyBigRequest;constructor(e){this.video=z(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?Z(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&&F(this.player),M(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:U})),!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'),(({mediaType:e,request:{url:s}})=>{const i=this.player.getDashMetrics(),a=i.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),r=i.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type')??exports.HttpConnectionType.HTTP1,o={1:!0,0:!1}[a]??void 0;this.params.output.httpConnectionType$.next(r),this.params.output.httpConnectionReused$.next(o),t.hostname$.next(de(s))})),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((()=>X(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(le(this.player,'playbackPlaying'),(()=>{this.videoState.setState(ce.PLAYING),S(s.playbackState,exports.PlaybackState.PLAYING)})),a(le(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(ce.PAUSED),S(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),S(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,connectionType$:u,connectionReused$:h}=V(this.player);a(u,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(n,this.maxSeekBackTime$),a(d.pipe(e.once()),t.firstBytesEvent$),a(le(this.player,'canPlay'),t.canplay$),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((()=>{this.subscription.add(le(this.player,'playbackPlaying').pipe(e.once(),e.mapTo(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(H(this.video,s.isLooped,i));const{volumeState$:c,looped$:l,playbackRateState$:p}=K(this.video);this.subscription.add(j(this.video,s.volume,c,i)),this.subscription.add(c.subscribe(t.volume$,i)),this.subscription.add(l.subscribe(t.loopedEvent$)),this.subscription.add(G(this.video,s.playbackRate,p,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(ce.STOPPED),S(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=f(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),S(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}},fe=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 Se(){return e.now()}function be(e){return Se()-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',f=7e3,S=2e3,b=()=>{if(c)return;e.assertNonNullable(u);const t=be(u);let s;if(t<S)return s=S-t,void setTimeout(b,s);S*=2,S>f&&(S=f),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=Se(),n=new r,n.open('get',t);let i,a=0,l=0;const f=()=>(e.assertNonNullable(u),Math.max(u,Math.max(i||0,l||0)));if(o&&n.addEventListener('progress',(e=>{const t=Se();o.updateChunk&&e.loaded>a&&(o.updateChunk(f(),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(f(),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=Se(),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)&&(S=t),e.isNonNullable(s)&&(f=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=Se(),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=Se()-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=Se()}_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=Se();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=>{const i=Boolean(e.error);console.log('Live HTMLVideoElement error','ignoring:',!i,{errorField:e.error,readyState:e.readyState,event:s,src:e.src}),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'),console.log('Live set 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.maxParallelRequests,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)},f=e=>{this.lowLatency=e,s(`lowLatency changed to ${e}`),S()},S=()=>{if(this.lowLatency){let e=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const t=Se()-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=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=t;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=i.dur.length-1;for(;r>=0&&(a-=i.dur[r],!(a<=0));--r);e=Math.min(r,i.dur.length-1-s),e=Math.max(e,0)}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&&f(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,f,v,y,T=b(t.jidxUrl),E=0;const k=()=>{f&&(clearTimeout(f),f=void 0);const e=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),t=E+e,s=Se(),i=Math.min(1e4,t-s);E=s;const a=()=>{u||c()&&T.seek((()=>{c()&&(E=Se(),w(),k())}))};i>0?f=window.setTimeout((()=>{this.paused?k():a()}),i):a()},w=()=>{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()},$=(e,t)=>{if(!c()||!this.sourceBuffer)return;let s,r,o;const n=s=>{window.setTimeout((()=>{c()&&$(e,t)}),s)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const d=Se(),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}),S(),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)}}},P=()=>{d&&n&&(a([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),$(d,(function(){d=null,w()})))},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}P()}}),(()=>this._handleNetworkError()))},N=t=>{c()&&(e.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(t),!1)))},R=e=>{c()&&(t.cachedHeader=e,$(e,(()=>{n=!0,P()})))};r=!0,T.seek((t=>{c()&&(E=Se(),t?(m=t,!e.isNullable(s)||t.startTS>s?x(t):(h=t,w())):k())}),s),t.cachedHeader?R(t.cachedHeader):l(t.headerUrl,R,(()=>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=Se();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=Se();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;fe(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 we=[ke.PAUSED,ke.PLAYING,ke.READY],$e=[ke.PAUSED,ke.PLAYING,ke.READY];class Pe{subscription=new e.Subscription;video;videoState=new k(ke.STOPPED);dash;representations$=new e.ValueSubject([]);textTracksManager=new Q;maxSeekBackTime$=new e.ValueSubject(1/0);zeroTime$=new e.ValueSubject(void 0);liveOffset=new W;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=z(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=K(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(G(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,s)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max: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:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger: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(f(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($e.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&&we.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(f(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 Re{_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(Re._str2ua(e.substr(n))),n=e.length};let p=e.baseURL+'&bytes='+t+'-'+s;this._params.requestQuic&&(p=U(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=Re._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=U(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?Z(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.to-this._video.currentTime,r<e.bufferLength&&(this._onDashCallback('buffering'),a!==t.to&&(a=t.to,window.setTimeout((()=>{try{const e=this._buffer.getNextWithGap(t);e&&(this._video.currentTime=e.from)}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 Re({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.to+a){const t=this._findRef(i.toTime);t&&t.toTime<s.to+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 _e;!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'}(_e||(_e={}));const Ce=[_e.PAUSED,_e.PLAYING];class Ie{videoState=new k(_e.STOPPED);subscription=new e.Subscription;video;buffer;dash;representations$=new e.ValueSubject([]);currentRepresentation$=new e.ValueSubject(void 0);params;textTracksManager=new Q;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=z(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=K(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.playing$,t.firstFrameEvent$),o(r.canplay$,t.canplay$),this.subscription.add(r.seeking$.subscribe((()=>{e.isNullable(this.params.desiredState.seekState.getState().state!==h.Applying)&&(this.videoState.getState()===_e.PLAYING||this.videoState.getState()===_e.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.subscription.add(G(this.video,s.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,s,t),o(ue(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===_e.READY&&this.videoState.setState(_e.READY)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(_e.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(_e.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),i)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(_e.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=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(e/i,1);u=ne(s.map((({track:e})=>e)),{container:n,throughput:o,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:s.find((({representation:e})=>e===t))?.track})?.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===_e.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(e.filter(e.isNonNullable))}).pipe(e.once()).subscribe((()=>this.videoState.setState(_e.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(),e.mapTo(void 0)).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(_e.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(){fe(this.video).then((e=>{e||(this.videoState.setState(_e.PAUSED),S(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&&Ce.includes(t)&&this.seek(r.position,r.forcePrecise),t){case _e.STOPPED:return this.videoState.startTransitionTo(_e.MANIFEST_LOADED),void this.prepare();case _e.MANIFEST_LOADED:return void this.videoState.startTransitionTo(_e.INITIAL_REPRESENTATION_SELECTED);case _e.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(_e.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case _e.METADATA_LOADED:return this.videoState.startTransitionTo(_e.READY),void this.dash.updateRefsForCurrentTime();case _e.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(_e.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(_e.PLAYING),this.playIfAllowed()));case _e.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(_e.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case _e.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(_e.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==_e.STOPPED&&(this.videoState.startTransitionTo(_e.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(_e.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))}}var Le,Be,Oe,Me,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.BYTE_RANGE='byteRange',e.TEMPLATE='template'}(Oe||(Oe={})),function(e){e.NONE='none',e.DOWNLOADING='downloading',e.DOWNLOADED='downloaded',e.PARTIALLY_FED='partially_fed',e.PARTIALLY_EJECTED='partially_ejected',e.FED='fed'}(Me||(Me={})),function(e){e.MP4='mp4',e.WEBM='webm'}(Ve||(Ve={}));var Ue=(e,t)=>{for(let s=0;s<e.length;s++){if(1e3*e.start(s)<=t&&1e3*e.end(s)>t)return!0}return!1};const Fe='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(e,t={})=>{const s=t.timeout||1,i=performance.now();return window.setTimeout((()=>{e({get didTimeout(){return!t.timeout&&performance.now()-i-1>s},timeRemaining:()=>Math.max(0,performance.now()-i+1)})}),1)}:window.requestIdleCallback;var qe=()=>{const{userAgent:e}=window.navigator;return!/chrome/i.test(e)&&/webkit|safari|khtml/i.test(e)};let He=!1;try{He=qe()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??'',10)<16}catch(e){console.error(e)}class je{bufferFull$=new e.Subject;error$=new e.Subject;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener('updateend',this.completeTask)}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()}))}async abort(e){return new Promise((t=>{let s;s=He&&e?{operation:'safariAbort',init:e,callback:t}:{operation:'abort',callback:t};for(const{callback:e}of this.queue)e(!1);s&&(this.queue=[s]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}completeTask=()=>{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:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(e){e instanceof DOMException&&'QuotaExceededError'===e.name&&'append'===t?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&'InvalidStateError'===e.name&&'remove'===t||this.error$.next({id:`BufferTaskQueue:${t}`,message:'Buffer operation failed',thrown:e}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(t){const{operation:s}=t;switch(s){case'append':this.buffer.appendBuffer(t.data);break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(t.init);break;default:e.assertNever(s)}}}var Ge,Ye=e=>{let t=0;for(let s=0;s<e.length;s++)t+=e.end(s)-e.start(s);return 1e3*t};!function(e){e[e.HEADER=0]='HEADER',e[e.PARAM=1]='PARAM'}(Ge||(Ge={}));class Qe{throughputEstimator;requestQuic;lastConnectionType$=new e.ValueSubject(void 0);lastConnectionReused$=new e.ValueSubject(void 0);lastRequestFirstBytes$=new e.ValueSubject(void 0);abortAllController=new C;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=U(t));const s=yield _(t,{signal:this.abortAllController.signal}).catch(ze);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=e.abortable(this.abortAllController.signal,async function*(t,{rangeMethod:s=Ge.HEADER,range:i,onProgress:a,priority:r='auto',signal:o,measureThroughput:n=!0}={}){let d=t;const u=new Headers;if(i)switch(s){case Ge.HEADER:u.append('Range',`${i.from}-${i.to}`);break;case Ge.PARAM:{const e=new URL(d,location.href);e.searchParams.append('bytes',`${i.from}-${i.to}`),d=e.toString();break}default:e.assertNever(s)}this.requestQuic&&(d=U(d));let h=this.abortAllController.signal;if(o){const t=new C;if(this.subscription.add(e.merge(e.fromEvent(this.abortAllController.signal,'abort'),e.fromEvent(o,'abort')).subscribe((()=>{try{t.abort()}catch(e){ze(e)}}))),this.abortAllController.signal.aborted||o.aborted)try{t.abort()}catch(e){ze(e)}h=t.signal}const c=e.now(),l=yield _(d,{priority:r,headers:u,signal:h}).catch(ze),p=e.now();if(this.throughputEstimator?.addRawRtt(p-c),!l)return null;if(!l.ok||!l.body)return Promise.reject(new Error(`Fetch error ${l.status}: ${l.statusText}`));this.onHeadersReceived(l.headers);const m=parseInt(l.headers.get('Content-Length')??'',10)||i&&i.to-i.from+1||NaN;if(!m){const t=yield l.arrayBuffer();return this.throughputEstimator?.addRawSpeed(t.byteLength,e.now()-p),a?.(new DataView(t),t.byteLength),t}if(!a&&!n)return l.arrayBuffer();const[f,S]=l.body.tee(),b=f.getReader();n&&this.throughputEstimator?.trackStream(S);let g=0;const v=new ArrayBuffer(m),y=new Uint8Array(v),T=new DataView(v);let E=!1;const k=e=>{E=!0,ze(e)},w=e.abortable(h,async function*({done:t,value:s}){0===g&&this.lastRequestFirstBytes$.next(e.now()-c),h.aborted||(t?a?.(T,g):s&&(y.set(s,g),g+=s.byteLength,a?.(T,g),yield b?.read().then(w,k)))}.bind(this));return yield b?.read().then(w,k),E?null:v}.bind(this));async fetchRepresentation(t,s,i='auto'){const{type:a}=t;switch(a){case Oe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(t,s,i)??null;case Oe.TEMPLATE:return await this.fetchTemplateRepresentation(t,i)??null;default:e.assertNever(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=e.abortable(this.abortAllController.signal,async function*(e,t,s){if(e.type!==Oe.BYTE_RANGE)return null;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);const h=yield this.fetch(e.url,{rangeMethod:Ge.PARAM,range:{from:n,to:d},priority:s,measureThroughput:!1});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 i=t.getIndexRange(l);if(i){const t=yield this.fetch(e.url,{rangeMethod:Ge.PARAM,range:i,priority:s,measureThroughput:!1});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));fetchTemplateRepresentation=e.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==Oe.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});if(!i)return null;return{segments:e.segments.map((e=>({...e,status:Me.NONE,size:void 0}))),dataView:new DataView(i)}}.bind(this))}const ze=e=>{if(!(e instanceof DOMException)||'AbortError'!==e.name&&20!==e.code)throw e},We=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=We.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)}},Xe={validateData:e=>'ftyp'===We.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=4294967295&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:Me.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 Ke,Ze;!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'}(Ke||(Ke={})),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'}(Ze||(Ze={}));const et={[Ke.EBML]:{type:Ze.Master},[Ke.EBMLVersion]:{type:Ze.UnsignedInteger},[Ke.EBMLReadVersion]:{type:Ze.UnsignedInteger},[Ke.EBMLMaxIDLength]:{type:Ze.UnsignedInteger},[Ke.EBMLMaxSizeLength]:{type:Ze.UnsignedInteger},[Ke.DocType]:{type:Ze.String},[Ke.DocTypeVersion]:{type:Ze.UnsignedInteger},[Ke.DocTypeReadVersion]:{type:Ze.UnsignedInteger},[Ke.Void]:{type:Ze.Binary},[Ke.Segment]:{type:Ze.Master},[Ke.SeekHead]:{type:Ze.Master},[Ke.Seek]:{type:Ze.Master},[Ke.SeekID]:{type:Ze.Binary},[Ke.SeekPosition]:{type:Ze.UnsignedInteger},[Ke.Info]:{type:Ze.Master},[Ke.TimestampScale]:{type:Ze.UnsignedInteger},[Ke.Duration]:{type:Ze.Float},[Ke.Tracks]:{type:Ze.Master},[Ke.Chapters]:{type:Ze.Master},[Ke.Cluster]:{type:Ze.Master},[Ke.Timestamp]:{type:Ze.UnsignedInteger},[Ke.SilentTracks]:{type:Ze.Master},[Ke.SilentTrackNumber]:{type:Ze.UnsignedInteger},[Ke.Position]:{type:Ze.UnsignedInteger},[Ke.PrevSize]:{type:Ze.UnsignedInteger},[Ke.SimpleBlock]:{type:Ze.Binary},[Ke.BlockGroup]:{type:Ze.Master},[Ke.EncryptedBlock]:{type:Ze.Binary},[Ke.Attachments]:{type:Ze.Master},[Ke.Tags]:{type:Ze.Master},[Ke.Cues]:{type:Ze.Master},[Ke.CuePoint]:{type:Ze.Master},[Ke.CueTime]:{type:Ze.UnsignedInteger},[Ke.CueTrackPositions]:{type:Ze.Master},[Ke.CueTrack]:{type:Ze.UnsignedInteger},[Ke.CueClusterPosition]:{type:Ze.UnsignedInteger},[Ke.CueRelativePosition]:{type:Ze.UnsignedInteger},[Ke.CueDuration]:{type:Ze.UnsignedInteger},[Ke.CueBlockNumber]:{type:Ze.UnsignedInteger},[Ke.CueCodecState]:{type:Ze.UnsignedInteger},[Ke.CueReference]:{type:Ze.Master},[Ke.CueRefTime]:{type:Ze.UnsignedInteger}},tt=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=st(e,s),a=i in et,r=a?et[i].type:Ze.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))+st(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}},st=(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},it=(t,s)=>{switch(s){case Ze.SignedInteger:return t.getInt8(0);case Ze.UnsignedInteger:return st(t);case Ze.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Ze.String:return new TextDecoder('ascii').decode(t);case Ze.UTF8:return new TextDecoder('utf-8').decode(t);case Ze.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Ze.Master:case Ze.Binary:return t;default:e.assertNever(s)}},at=(e,t)=>{let s=0;for(;s<e.byteLength;){const i=new DataView(e.buffer,e.byteOffset+s),a=tt(i);if(!t(a))return;a.type===Ze.Master&&at(a.value,t),s=a.value.byteOffset-e.byteOffset+a.valueSize}},rt=[Ke.Info,Ke.SeekHead,Ke.Tracks,Ke.Chapters,Ke.Cluster,Ke.Cues,Ke.Attachments,Ke.Tags],ot=[Ke.Timestamp,Ke.SilentTracks,Ke.SilentTrackNumber,Ke.Position,Ke.PrevSize,Ke.SimpleBlock,Ke.BlockGroup,Ke.EncryptedBlock],nt={validateData:e=>{if(e.getUint32(0)!==Ke.EBML)return!1;let t,s,i;const a=tt(e);return at(a.value,(({tag:e,type:a,value:r})=>(e===Ke.EBMLReadVersion?t=it(r,a):e===Ke.DocType?s=it(r,a):e===Ke.DocTypeReadVersion&&(i=it(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 at(t,(({tag:e,type:t,value:c,valueSize:l})=>{if(e===Ke.SeekID){const e=it(c,t);n=st(e)}else e!==Ke.SeekPosition&&(n=void 0);return e===Ke.Segment?(s=c.byteOffset,i=c.byteOffset+l):e===Ke.Info?d=!0:e===Ke.SeekHead?u=!0:e===Ke.TimestampScale?a=it(c,t):e===Ke.Duration?r=it(c,t):e===Ke.SeekPosition&&n===Ke.Cues?o=it(c,t):d&&u&&rt.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 at(t,(({tag:e,type:t,value:s})=>{switch(e){case Ke.Cues:i=!0;break;case Ke.CuePoint:n&&r(n)&&o.push(n),n={};break;case Ke.CueTime:n&&(n.time=it(s,t));break;case Ke.CueTrackPositions:break;case Ke.CueClusterPosition:n&&(n.position=it(s,t));break;default:i&&rt.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:Me.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{at(e,(i=>i.tag===Ke.Cluster?i.tagSize<=e.byteLength?(t=i.tagSize,!1):(t+=i.tagHeaderSize,!0):!!ot.includes(i.tag)&&(t+i.tagSize<=e.byteLength&&(t+=i.tagSize,s||=[Ke.SimpleBlock,Ke.BlockGroup,Ke.EncryptedBlock].includes(i.tag)),!0)))}catch(e){}return t>0&&t<=e.byteLength&&s?new DataView(e.buffer,e.byteOffset,t):null}};class dt{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;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new C;destroyAbortController=new C;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;constructor(t,s,i,a,{fetcher:r,tuning:o,getCurrentPosition:n}){switch(this.fetcher=r,this.tuning=o,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.container=i,i){case Ve.MP4:this.containerParser=Xe;break;case Ve.WEBM:this.containerParser=nt;break;default:e.assertNever(i)}this.initData=new Map(a.map((e=>[e.id,null]))),this.segments=new Map,this.representations=new Map(a.map((e=>[e.id,e]))),this.kind=t,this.mediaSource=s,this.sourceBuffer=null}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 je(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((()=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((e=>{if(!this.sourceBuffer)return;const t=Math.min(this.bufferLimit,Ye(this.sourceBuffer.buffered));this.bufferLimit=t,this.pruneBuffer(e)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((e=>this.error$.next(e)))),yield this.loadInit(s,'high',!0);const i=this.initData.get(s.id),a=this.segments.get(s.id);if(e.assertNonNullable(i,'No init buffer for starting representation'),e.assertNonNullable(a,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let r=0;for(const e of a)e.time.from-r>=300&&this.gaps.push({representation:s.id,from:r,to:e.time.from}),r=e.time.to;e.isNonNullable(s.duration)&&s.duration-r>=300&&this.gaps.push({representation:s.id,from:r,to:s.duration}),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=e.abortable(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;this.switchingToRepresentationId=t;const s=this.representations.get(t);e.assertNonNullable(s,`No such representation ${t}`);let i=this.initData.get(t);if(e.isNullable(i)?yield this.loadInit(s,'high',!1):i instanceof Promise&&(yield i),i=this.initData.get(t),!(i&&i instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal);const a=this.getCurrentPosition();e.isNonNullable(a)&&this.maintain(a)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new C,this.abortBuffer()}maintain(t){if(e.isNullable(this.downloadingRepresentationId)||e.isNullable(this.playingRepresentationId)||e.isNullable(this.sourceBuffer))return;const s=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(e.assertNonNullable(s,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,s=xe(this.sourceBuffer.buffered,t),i=a?a.time.to+e:-1/0;a&&s>=a.time.to-t+e&&(r=i)}if(isFinite(this.bufferLimit)&&Ye(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),a&&a.status!==Me.NONE))return;let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,s.segmentReference.type,r),o.length)){let e='auto';if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))e='high';else{const t=o.at(0);t&&t.time.from-a.time.to>=this.forwardBufferTarget/2&&(e='low')}this.loadSegments(o,s,e)}!this.allInitsLoaded&&a&&a.status===Me.FED&&!o.length&&xe(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const n=i.at(-1);n&&n.status===Me.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===n))}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}setTarget(e){this.forwardBufferTarget=e}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex((({status:e,time:{from:t,to:i}})=>e===Me.NONE&&(t>s||t<=s&&i>=s)&&i<=s+this.forwardBufferTarget));if(-1===i)return[];if(t!==Oe.BYTE_RANGE)return e.slice(i,i+1);const a=e;let r=0;const o=[];for(let e=i;e<a.length&&r<=this.tuning.dash.segmentRequestSize;e++){const t=a[e];if(r+=t.byte.to+1-t.byte.from,t.status!==Me.NONE&&t.status!==Me.PARTIALLY_EJECTED)break;o.push(t)}return o}async loadSegments(t,s,i='auto'){if(!t.length)return;let a,r,o=t;const{type:n}=s.segmentReference;switch(n){case Oe.BYTE_RANGE:a=s.segmentReference.url,r={from:t.at(0).byte.from,to:t.at(-1).byte.to};break;case Oe.TEMPLATE:{const e=t.at(0);a=new URL(e.url,s.segmentReference.baseUrl).toString(),o=[e];break}default:e.assertNever(n)}for(const e of o)e.status=Me.DOWNLOADING,this.activeSegments.add({segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:s.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await e.abortable(d,async function*(){const t=e.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))(),d.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(a,{rangeMethod:Ge.PARAM,range:r,onProgress:(e,t)=>{if(!d.aborted)try{this.onSomeDataLoaded(e,s.id,r?r.from:0,t,d)}catch(e){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:e})}},signal:d,priority:i}).then((()=>this.failedDownloads=0),(e=>{for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.onSegmentDownloadError(e)}))}onSegmentDownloadError(t){let s=!1;const i=this.getCurrentPosition();if(this.sourceBuffer&&e.isNonNullable(i)){s=xe(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,s||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}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=Me.FED,'size'in e.segment&&(e.segment.size=e.fedBytes);for(const s of this.representations.values())if(s.id!==t)for(const t of this.segments.get(s.id)??[])t.status===Me.FED&&t.time.from===e.segment.time.from&&t.time.to===e.segment.time.to&&(t.status=Me.NONE);this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])},n=this.representations.get(t);if(!n)return;const d=n.segmentReference.type,u=e.byteLength;for(const n of this.activeSegments){const{segment:h}=n,c=d===Oe.BYTE_RANGE,l=c?h.byte.to-h.byte.from+1:u;if(n.representationId!==t)continue;if(!(!c||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){r(n);continue}const p=c?h.byte.from-s:0,m=p<i,f=(c?h.byte.to-s:e.byteLength)<=i;if(h.status===Me.DOWNLOADING&&m&&f){h.status=Me.DOWNLOADED,this.activeSegments.delete(n);const t=new DataView(e.buffer,e.byteOffset+p,l);this.sourceBufferTaskQueue.append(t,a).then((e=>e&&!a.aborted?o(n):r(n)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(n.loadedBytes=Math.min(l,i-p),n.loadedBytes>n.feedingBytes)){const t=new DataView(e.buffer,e.byteOffset+p+n.feedingBytes,n.loadedBytes-n.feedingBytes),s=n.loadedBytes===l?t:this.containerParser.parseFeedableSegmentChunk(t);s?.byteLength&&(h.status=Me.PARTIALLY_FED,n.feedingBytes+=s.byteLength,this.sourceBufferTaskQueue.append(s,a).then((e=>{if(a.aborted)r(n);else if(e)n.fedBytes+=s.byteLength,n.fedBytes===l&&o(n);else{if(n.feedingBytes<l)return;r(n)}})))}}}abortSegment(e){e.status===Me.PARTIALLY_FED||e.status===Me.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then((()=>e.status=Me.NONE)),e.status=Me.PARTIALLY_EJECTED):e.status=Me.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,i]of this.initData.entries()){const a=i instanceof Promise;t||=a,null===i&&(e=s)}if(!e)return void(this.allInitsLoaded=!0);if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Fe((()=>this.loadInit(s,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,s='auto',i=!1){const a=this.tuning.dash.useFetchPriorityHints?s:'auto',r=(!i&&this.failedDownloads>0?e.abortable(this.destroyAbortController.signal,async function*(){const t=e.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a))).then((e=>{if(!e)return;const{dataView:s,segments:i}=e,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(t.id,a),this.segments.set(t.id,i)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,r),r}async pruneBuffer(t){const 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;const d=e=>{r=Math.min(r,e.time.from),o=Math.max(o,e.time.to);const t='size'in e?e.size??0:e.byte.to-e.byte.from;a+=t};for(const e of i){if(e.time.to>=s||a>=t)break;e.status===Me.FED&&d(e)}if(n=isFinite(r)&&isFinite(o),!n){a=0,r=1/0,o=-1/0;for(const e of i){if(e.time.from<s+this.forwardBufferTarget||a>t)break;e.status===Me.FED&&d(e)}}if(n=isFinite(r)&&isFinite(o),!n)for(let e=0;e<this.sourceBuffer.buffered.length;e++){const t=1e3*this.sourceBuffer.buffered.start(e),s=1e3*this.sourceBuffer.buffered.end(e);for(const e of i)if(e.status===Me.NONE&&Math.round(e.time.from)<=Math.round(t)&&Math.round(e.time.to)>=Math.round(s)){r=t,o=s;break}}return n=isFinite(r)&&isFinite(o),!!n&&this.sourceBufferTaskQueue.remove(r,o)}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fe((()=>{try{this.detectGaps(e,t)}catch(e){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:e})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(e.isNullable(this.sourceBuffer)||e.isNullable(this.playingRepresentationId))return;const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const s=Math.round(1e3*this.sourceBuffer.buffered.start(e)),i=Math.round(1e3*this.sourceBuffer.buffered.end(e));t.push({from:s,to:i})}for(const e of this.segments.values())for(const s of e){const{status:e}=s;if(e!==Me.FED&&e!==Me.PARTIALLY_EJECTED)continue;const i=Math.round(s.time.from),a=Math.round(s.time.to),r=t.some((e=>e.from<=i&&e.to>=a)),o=t.some((e=>i>e.from&&i<e.to||a>e.from&&a<e.to));r||(s.status=o?Me.PARTIALLY_EJECTED:Me.NONE)}}}const ut=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*60*1e3+60*t(s?.[6],i)*60*1e3+60*t(s?.[7],i)*1e3+1e3*t(s?.[8],i)},ht=(t,s)=>{let i=t;i=i.replaceAll('$$','$');const a={RepresentationID:s.representationId,Number:s.segmentNumber,Bandwidth:s.bandwidth,Time:s.segmentTime};for(const[t,s]of Object.entries(a)){const a=new RegExp(`\\$${t}(?:%0(\\d+)d)?\\$`,'g');i=i.replaceAll(a,((t,i)=>e.isNullable(s)?t:e.isNullable(i)?s:s.padStart(parseInt(i,10),'0')))}return i},ct=['timeupdate','progress','play','seeked','stalled'];var lt,pt;!function(e){e.NONE='none',e.MANIFEST_LOADED='manifest_loaded',e.REPRESENTATION_SELECTED='representation_selected'}(lt||(lt={}));class mt{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new e.Subscription;fetcher;state$=new k(lt.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 C;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Qe({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=e.abortable(this.destroyController.signal,async function*(t,s){this.element=t,this.state$.startTransitionTo(lt.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(s).catch((e=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:e})));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=ut(d);else if(u){const t=ut(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');if('text'!==r)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(',')??[],f=parseInt(u.getAttribute('width')??'',10),S=parseInt(u.getAttribute('height')??'',10),b=parseInt(u.getAttribute('bandwidth')??'',10)/1e3,g=u.getAttribute('frameRate')??'',v=u.getAttribute('quality')??void 0,y=g?Z(g):void 0,T=`${u.getAttribute('id')??(h++).toString(10)}@${'video'===p?`${S}p`:'audio'===p?`${b}Kbps`:l}`,E=u.querySelector('BaseURL')?.textContent?.trim()??'',k=new URL(E,s).toString(),w=[...c,...o,...m];let $;const P=u.querySelector('SegmentBase'),A=u.querySelector('SegmentTemplate');if(P){const e=u.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[t,s]=e.split('-').map((e=>parseInt(e,10))),i={from:t,to:s},a=u.querySelector('SegmentBase')?.getAttribute('indexRange'),[r,o]=a?a.split('-').map((e=>parseInt(e,10))):[],n=a?{from:r,to:o}:void 0;$={type:Oe.BYTE_RANGE,url:k,initRange:i,indexRange:n}}else{if(!A)throw new ReferenceError('Unknown MPD segment referencing type');{const e={representationId:u.getAttribute('id')??void 0,bandwidth:u.getAttribute('bandwidth')??void 0},t=parseInt(A.getAttribute('timescale')??'',10),s=A.getAttribute('initialization')??'',i=A.getAttribute('media'),a=parseInt(A.getAttribute('startNumber')??'',10)??1,r=ht(s,e);if(!i)throw new ReferenceError('No media attribute in SegmentTemplate');const o=A.querySelectorAll('SegmentTimeline S')??[],n=[];let d=a,h=0;for(const s of o){const a=1e3*parseInt(s.getAttribute('d')??'',10),r=parseInt(s.getAttribute('r')??'',10)||0,o=parseInt(s.getAttribute('t')??'',10)??void 0;for(let s=0;s<r+1;s++){const s=ht(i,{...e,segmentNumber:d.toString(10),segmentTime:o.toString(10)}),r=o?o/t:h;h+=a/t;const u=h;d++,n.push({time:{from:r,to:u},url:s})}}$={type:Oe.TEMPLATE,baseUrl:k,initUrl:r,segments:n}}}if(!p||!d)continue;const x={video:Le.VIDEO,audio:Le.AUDIO,text:Le.TEXT}[p];x&&i[x].push({id:T,kind:x,segmentReference:$,profiles:w,duration:n,bitrate:b,mime:d,codecs:l,width:f,height:S,fps:y,quality:v})}}return{duration:n,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(lt.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(lt.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new dt(Le.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],e.isNonNullable(s)&&(this.audioBufferManager=new dt(Le.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=e.merge(...this.bufferManagers.map((e=>e.fullyBuffered$))).pipe(e.map((()=>this.bufferManagers.every((e=>e.fullyBuffered$.getValue()))))),r=e.merge(...this.bufferManagers.map((e=>e.onLastSegment$))).pipe(e.map((()=>this.bufferManagers.some((e=>e.onLastSegment$.getValue())))));this.subscription.add(e.merge(this.forceEnded$,e.combine({allBuffersFull:a,someBufferEnded:r}).pipe(e.filter((({allBuffersFull:e,someBufferEnded:t})=>e&&t)))).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.bufferManagers.map((e=>e.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)))),e.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&e.isNonNullable(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(lt.REPRESENTATION_SELECTED),e.assertNonNullable(this.element),this.subscription.add(e.merge(...ct.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((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&Ue(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this));async switchRepresentation(e,t){return{[Le.VIDEO]:this.videoBufferManager,[Le.AUDIO]:this.audioBufferManager,[Le.TEXT]:null}[e]?.switchTo(t)}seek(t,s){let i;e.assertNonNullable(this.element),e.assertNonNullable(this.videoBufferManager),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),Ue(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(lt.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager?.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager?.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=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)return;const e=1e3*this.element.currentTime,t=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const s of this.bufferManagers)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'}(pt||(pt={}));const ft=({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}},St=(e,t,s)=>{const i=t.indexOf(s);return e.at(Math.round(e.length*i/t.length))??e.at(-1)};class bt{subscription=new e.Subscription;videoState=new k(pt.STOPPED);video;player;params;elementSize$=new e.ValueSubject(void 0);textTracksManager=new Q;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new oe;constructor(e){this.params=e,this.video=z(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 mt({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:s}=this.params,i=K(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.playing$,t.firstFrameEvent$),r(i.canplay$,t.canplay$),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(),e.mapTo(void 0)),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)),this.subscription.add(G(this.video,s.playbackRate,i.playbackRateState$,a)),r(ue(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(pt.PLAYING),S(s.playbackState,exports.PlaybackState.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(pt.PAUSED),S(s.playbackState,exports.PlaybackState.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===pt.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(e.filter((({to:e})=>e===lt.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(pt.READY)})));const o=e=>t.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:e});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 i=this.player.state$.getState(),a=this.player.state$.getTransition();if(i===lt.NONE||!this.videoTracks.length)return;const r=i===lt.MANIFEST_LOADED&&!a,n=i===lt.REPRESENTATION_SELECTED&&!a,d=s.autoVideoTrackSwitching.getState(),u=s.videoTrack.getState(),h=this.videoTracks.find((({track:{id:e}})=>e===u))?.track,c=t.currentVideoTrack$.getValue(),l=xe(this.video.buffered,1e3*this.video.currentTime),p=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(l/Math.min(p,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),f=Math.max(h&&!d?this.audioRepresentations.get(h.id)?.bitrate??0:0,c?this.audioRepresentations.get(c.id)?.bitrate??0:0),S=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(),reserve:f,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),b=d?S??h:h??S;if(s.autoVideoTrackSwitching.getTransition()&&(s.autoVideoTrackSwitching.setState(d),this.player.setBufferTarget(p)),r){const t=b&&this.videoTracks.find((({track:e})=>e===b))?.representation;e.assertNonNullable(t),this.player.initRepresentations(t.id,this.audioRepresentations.get(t.id)?.id)}else if(n){const e=b&&this.videoTracks.find((({track:e})=>e===b))?.representation;if(e){const t=this.audioRepresentations.get(e.id);this.player.switchRepresentation(Le.VIDEO,e.id).catch(o),t&&this.player.switchRepresentation(Le.AUDIO,t.id).catch(o)}}}),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 n=e.merge(s.playbackState.stateChangeStarted$,s.videoTrack.stateChangeStarted$,s.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,a))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort(((e,t)=>t.bitrate-e.bitrate)),s=Array.from(e.representations.video).sort(((e,t)=>t.bitrate-e.bitrate));for(const e of s){const i=ft(e);if(i){this.videoTracks.push({track:i,representation:e});const a=St(t,s,e);a&&this.audioRepresentations.set(e.id,a)}}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!==pt.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),s!==exports.PlaybackState.STOPPED){if(t===pt.STOPPED)return this.videoState.startTransitionTo(pt.READY),void this.prepare();switch(t){case pt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(pt.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(pt.PLAYING),this.playIfAllowed()));case pt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(pt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case pt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(pt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}else t!==pt.STOPPED&&(this.videoState.startTransitionTo(pt.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(pt.STOPPED),S(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(){fe(this.video).then((e=>{e||(this.videoState.setState(pt.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const gt={};var vt;!function(e){e.INITIALIZING='initializing',e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(vt||(vt={}));const yt=(t,s)=>new e.Observable((e=>{const i=(t,s)=>e.next(s);return t.on(s,i),()=>t.off(s,i)}));class Tt{subscription=new e.Subscription;videoState=new k(vt.INITIALIZING);video;params;hls;textTracksManager=new Q;trackLevels=new Map;constructor(e){this.video=z(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||(gt.Hls=t.default,gt.Events=t.default.Events,this.init())}),t).finally((()=>{window.clearTimeout(i),e=!0}))}init(){e.assertNonNullable(gt.Hls,'hls.js not loaded'),this.hls=new gt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(vt.STOPPED)}subscribe(){e.assertNonNullable(gt.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=K(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.loadStart$,s.firstBytesEvent$),r(a.playing$,s.firstFrameEvent$),r(a.canplay$,s.canplay$),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(G(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(yt(this.hls,gt.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(vt.PLAYING),S(t.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(vt.PAUSED),S(t.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===vt.READY&&this.videoState.setState(vt.READY),this.videoState.getState()===vt.PLAYING&&this.playIfAllowed()}),i)),r(yt(this.hls,gt.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(yt(this.hls,gt.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=yt(this.hls,gt.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!==vt.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===h.Requested&&this.seek(a.position),s){case exports.PlaybackState.STOPPED:switch(t){case vt.STOPPED:break;case vt.READY:case vt.PLAYING:case vt.PAUSED:this.stop();break;default:e.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case vt.PLAYING:break;case vt.STOPPED:this.prepare();break;case vt.READY:case vt.PAUSED:this.playIfAllowed();break;default:e.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case vt.PAUSED:break;case vt.STOPPED:this.prepare();break;case vt.READY:this.videoState.setState(vt.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case vt.PLAYING:this.pause();break;default:e.assertNever(t)}break;default:e.assertNever(s)}};prepare(){this.videoState.startTransitionTo(vt.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(vt.PLAYING);await fe(this.video)||(this.videoState.setState(vt.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(vt.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(vt.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}var Et=async e=>{const t=await _(e,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0};const kt=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},wt=async(e,t=e)=>{const s=await _(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=kt(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 $t,Pt,At;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.CHANGING_MANIFEST='changing_manifest',e.PAUSED='paused'}($t||($t={}));class xt{subscription=new e.Subscription;videoState=new k($t.STOPPED);video;params;textTracksManager=new Q;manifests$=new e.ValueSubject([]);maxSeekBackTime$;liveOffset=new W;manifestStartTime$=new e.ValueSubject(void 0);constructor(t){this.params=t,this.video=z(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]),wt(f(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=K(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.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),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.subscription.add(G(this.video,s.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState($t.PLAYING),S(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState($t.PAUSED),S(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===$t.READY&&this.videoState.setState($t.READY),this.videoState.getState()===$t.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===$t.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=f(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',s),this.video.load(),Et(s).then((t=>{if(e.isNullable(t)){const t=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(e.isNullable(t)||!isFinite(t))try{_(s).then((e=>e.text())).then((t=>{const i=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(t)?.[1];if(i){const t=new URL(i,s).toString();Et(t).then((t=>{e.isNullable(t)||this.maxSeekBackTime$.next(t)}))}}))}catch(e){}}else this.maxSeekBackTime$.next(t)}))}playIfAllowed(){fe(this.video).then((e=>{e||(this.videoState.setState($t.PAUSED),this.liveOffset.pause(),S(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!==$t.STOPPED&&(this.videoState.startTransitionTo($t.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($t.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===$t.STOPPED)return this.videoState.startTransitionTo($t.READY),void this.prepare();if(a||r){const e=this.videoState.getState();return this.videoState.setState($t.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($t.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case $t.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState($t.PAUSED),this.liveOffset.pause(),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($t.PLAYING),this.playIfAllowed()));case $t.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo($t.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case $t.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo($t.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&&(S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case $t.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'}(Pt||(Pt={}));class Nt{subscription=new e.Subscription;videoState=new k(Pt.STOPPED);video;params;textTracksManager=new Q;manifests$=new e.ValueSubject([]);constructor(e){this.params=e,this.video=z(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)),wt(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=K(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.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),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(G(this.video,s.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,s,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Pt.PLAYING),S(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Pt.PAUSED),S(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Pt.READY&&this.videoState.setState(Pt.READY),this.videoState.getState()===Pt.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===Pt.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(){fe(this.video).then((e=>{e||(this.videoState.setState(Pt.PAUSED),S(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!==Pt.STOPPED&&(this.videoState.startTransitionTo(Pt.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(Pt.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(t===Pt.STOPPED)return this.videoState.startTransitionTo(Pt.READY),void this.prepare();if(a||r){const e=this.videoState.getState();this.videoState.setState(Pt.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 Pt.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Pt.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Pt.PLAYING),this.playIfAllowed()));case Pt.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Pt.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Pt.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Pt.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Pt.CHANGING_MANIFEST:break;default:return e.assertNever(t)}}}!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(At||(At={}));class Rt{subscription=new e.Subscription;videoState=new k(At.STOPPED);video;trackUrls={};params;textTracksManager=new Q;constructor(e){this.params=e,this.video=z(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.params.desiredState.autoVideoTrackSwitching.setState(!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=K(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.loadedMetadata$,t.firstBytesEvent$),r(a.playing$,t.firstFrameEvent$),r(a.canplay$,t.canplay$),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(G(this.video,s.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(At.PLAYING),S(s.playbackState,exports.PlaybackState.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(At.PAUSED),S(s.playbackState,exports.PlaybackState.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===At.READY&&this.videoState.setState(At.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()===At.PLAYING&&this.playIfAllowed()}),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=U(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(de(s))}playIfAllowed(){fe(this.video).then((e=>{e||(this.videoState.setState(At.PAUSED),S(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!==At.STOPPED&&(this.videoState.startTransitionTo(At.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(At.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(t===At.STOPPED)return this.videoState.startTransitionTo(At.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 At.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(At.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(At.PLAYING),this.playIfAllowed()));case At.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(At.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case At.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(At.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}const Dt=['stun:videostun.mycdn.me:80'],_t=()=>null;class Ct{options;ws=null;peerConnection=null;serverUrl='';streamKey='';stream=null;signalingType='JOIN';retryTimeout;retryCount=0;externalStartCallback=_t;externalStopCallback=_t;externalErrorCallback=_t;constructor(e,t){this.options=this.normalizeOptions(t);const s=e.split('/');this.serverUrl=s.slice(0,s.length-1).join('/'),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(e){this.handleSystemError(e)}}onStop(e){try{this.externalStopCallback=e}catch(e){this.handleSystemError(e)}}onError(e){try{this.externalErrorCallback=e}catch(e){this.handleSystemError(e)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(e){this.handleRTCError(e)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(e){this.handleRTCError(e)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case'JOIN':case'CALL_JOIN':this.handleJoinMessage(t);break;case'UPDATE':this.handleUpdateMessage(t);break;case'STATUS':this.handleStatusMessage(t)}}catch(e){this.handleRTCError(e)}}handleJoinMessage(e){switch(e.inviteType){case'ANSWER':this.handleAnswer(e.sdp);break;case'CANDIDATE':this.handleCandidate(e.candidate)}}handleStatusMessage(e){switch(e.status){case'UNPUBLISHED':this.handleUnpublished()}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(e){this.handleRTCError(e)}}async handleLogin(){try{const e={iceServers:[{urls:Dt}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:e}))}catch(e){this.handleRTCError(e)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(e){this.handleRTCError(e)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:'CANDIDATE',candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;['failed','closed'].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}),t=e.sdp||'';if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(t))throw new Error('No h264 codec support error');return e}handleRTCError(e){try{this.externalErrorCallback(e||new Error('RTC connection error'))}catch(e){this.handleSystemError(e)}}handleNetworkError(){try{this.externalErrorCallback(new Error('Network error'))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(e){throw new Error('Can not parse socket message')}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),1e3)}normalizeOptions(e={}){const t={stunServerList:Dt,maxRetryNumber:3,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var It;!function(e){e.STOPPED='stopped',e.READY='ready',e.PLAYING='playing',e.PAUSED='paused'}(It||(It={}));class Lt{subscription;params;log;video;videoState=new k(It.STOPPED);liveStreamClient;maxSeekBackTime$=new e.ValueSubject(0);constructor(t){this.subscription=new e.Subscription,this.params=t,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=z(t.container),this.liveStreamClient=new Ct(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:t,desiredState:s}=this.params,i=e=>{t.error$.next({id:'WebRTCLiveProvider',message:'WebRTCLiveProvider 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)}`})}));const a=K(this.video),r=(e,t)=>this.subscription.add(e.subscribe(t,i));r(a.timeUpdate$,t.liveTime$),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$),this.subscription.add(a.durationChange$.subscribe((e=>{t.duration$.next(e===1/0?0:e)}))).add(a.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===It.READY&&this.videoState.setState(It.READY)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(It.PAUSED)}),i)).add(a.playing$.subscribe((()=>{this.videoState.setState(It.PLAYING)}),i)).add(a.error$.subscribe(t.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(j(this.video,s.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(t.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe((i=>{switch(i.to){case It.STOPPED:t.position$.next(0),t.duration$.next(0),s.playbackState.setState(exports.PlaybackState.STOPPED);break;case It.READY:break;case It.PAUSED:s.playbackState.setState(exports.PlaybackState.PAUSED);break;case It.PLAYING:s.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return e.assertNever(i.to)}}),i)).add(e.merge(s.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,e.observableFrom(['init'])).pipe(e.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(s.isLooped.stateChangeStarted$.subscribe((()=>s.isLooped.setState(!1)),i)),this.subscription.add(s.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>s.autoVideoTrackSwitching.setState(!1)),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(It.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',message:e.message,thrown:e})}playIfAllowed(){fe(this.video).then((e=>{e||(this.videoState.setState(It.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}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!==It.STOPPED&&(this.videoState.startTransitionTo(It.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(It.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(t===It.STOPPED)return this.videoState.startTransitionTo(It.READY),void this.prepare();if(a)this.prepare();else switch(t){case It.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(It.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(It.PLAYING),this.playIfAllowed()));case It.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(It.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case It.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(It.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return e.assertNever(t)}}}class Bt{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 Ot=qe(),Mt=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Vt=document.createElement('video'),Ut={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Vt.canPlayType?.('application/x-mpegurl')||Vt.canPlayType?.('vnd.apple.mpegURL')),webrtc:Boolean(window.RTCPeerConnection)},Ft={mp4:Boolean(Vt.canPlayType?.('video/mp4')),webm:Boolean(Vt.canPlayType?.('video/webm'))},qt={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"'))},Ht=(qt.h264||qt.h265)&&qt.aac,jt=!Ot,Gt=Ut.hls&&Ft.mp4&&(Mt||Ot),Yt=Boolean(window.WebSocket);const Qt=3e4,zt=18e4,Wt=3,Jt=100,Xt={cacheDuration:12e4},Kt={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Zt={maxPausedTime:3e4},es={maxPausedTime:3e4};class ts{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,canplay$: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 Bt(((t,s=!1)=>t.filter((t=>{switch(t){case exports.VideoFormat.DASH:return Ut.mse&&Ft.mp4&&Ht&&jt;case exports.VideoFormat.DASH_SEP:return Ut.mse&&Ft.mp4&&Ht;case exports.VideoFormat.DASH_WEBM:return Ut.mse&&Ft.webm&&qt.vp9&&qt.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return Ut.mse&&Ft.mp4&&Ht;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return Gt||s&&Ut.mse&&Ft.mp4&&Ht;case exports.VideoFormat.MPEG:return Ft.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ut.webrtc&&Yt&&qt.h264&&(Ft.mp4||Ft.webm);default:return e.assertNever(t)}})))(i.filter((s=>e.isNonNullable(t.sources[s]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Bt(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=1e3*this.providerOutput.position$.getValue(),s=this.params.desiredState.seekState.getState(),i=s.state!==h.None;this.params.desiredState.seekState.setState({state:h.Requested,position:i?s.position:t,forcePrecise:!!i&&s.forcePrecise}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.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,o={container:i,source:null,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case exports.VideoFormat.DASH:{const i=s[t];return e.assertNonNullable(i),new Ie({...o,source:i,config:Xt})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const i=s[t];return e.assertNonNullable(i),this.params.tuning.useDashJs?new pe({...o,source:i,format:t,config:es}):new bt({...o,source:i})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[t];return e.assertNonNullable(i),Gt||!this.params.tuning.useHlsJs?new Nt({...o,source:i}):new Tt({...o,source:i})}case exports.VideoFormat.HLS_LIVE:{const i=s[t];return e.assertNonNullable(i),new xt({...o,source:i,config:Zt})}case exports.VideoFormat.MPEG:{const i=s[t];return e.assertNonNullable(i),new Rt({...o,source:i})}case exports.VideoFormat.DASH_LIVE:{const i=s[t];return e.assertNonNullable(i),new Pe({...o,source:i,config:Kt})}case exports.VideoFormat.WEB_RTC_LIVE:{const o=s[t];return e.assertNonNullable(o),new Lt({container:i,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return 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 $({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:Qt,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(e.filter((({type:e})=>void 0!==e)))},new e.Observable((t=>{const s=new e.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(e.map((({from:e,to:t})=>`${e}-${t}`))),r=a.desiredPlaybackState$.stateChangeEnded$,o=a.providerChanged$,n=new e.Subject;let d=0,u='unknown';return s.add(i.subscribe((e=>{d&&window.clearTimeout(d),u=e,d=window.setTimeout((()=>n.next(e)),a.maxTransitionInterval)}))),s.add(r.subscribe((()=>{window.clearTimeout(d),u='provider change',d=0}))),s.add(o.subscribe((()=>{d&&(window.clearTimeout(d),d=window.setTimeout((()=>n.next(u)),a.maxTransitionInterval))}))),s.add(n.subscribe(t)),()=>{window.clearTimeout(d),s.unsubscribe()}}))).pipe(e.map((e=>({id:`ProviderHangup:${e}`,message:`A ${e} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),i.add(this.providerError$.pipe(e.throttle(Jt,{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]+zt?(t=[],this.switchToNextProvider()):(t[s]=i,this.reinitProvider()),s=(s+1)%Wt}))),i}}const ss=(e,t,s)=>s*t+(1-s)*e;class is{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(t){this.params=t,this.pastMeasures=Array(t.deviationDepth),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 ae(`raw_${s}`),this.smoothedSeries$=new ae(`smoothed_${s}`),this.reportedSeries$=new ae(`reported_${s}`),this.rawSeries$.next(t.initial),this.smoothedSeries$.next(t.initial),this.reportedSeries$.next(t.initial)}next(t){let s=0,i=0;for(let e=0;e<this.pastMeasures.length;e++)void 0!==this.pastMeasures[e]&&(s+=(this.pastMeasures[e]-this.smoothed)**2,i++);s/=i;const a=Math.sqrt(s),r=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=t,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(t),this.slow=ss(this.slow,t,this.params.emaAlphaSlow),this.fast=ss(this.fast,t,this.params.emaAlphaFast);const n=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=n(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>r||this.smoothed<o||(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))}}var as;!function(e){e[e.LOCAL_STORAGE=0]='LOCAL_STORAGE',e[e.SESSION_STORAGE=1]='SESSION_STORAGE',e[e.RUNTIME=2]='RUNTIME'}(as||(as={}));const rs=new Map;let os=as.RUNTIME;const ns=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(ns,'test'),localStorage.removeItem(ns),os=as.LOCAL_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;try{sessionStorage.getItem(ns),os=as.SESSION_STORAGE}catch(e){if(!(e instanceof DOMException||e instanceof TypeError))throw e;os=as.RUNTIME}}})();const ds=(t,s)=>{switch(os){case as.LOCAL_STORAGE:try{localStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case as.SESSION_STORAGE:try{sessionStorage.setItem(t,s)}catch(e){if(!(e instanceof DOMException))throw e;console.error(e)}break;case as.RUNTIME:return void rs.set(t,s);default:e.assertNever(os)}},us=window.navigator.connection,hs=()=>{const t=us?.downlink;if(e.isNonNullable(t)&&10!==t)return 1e3*t},cs=()=>{const t=us?.rtt;if(e.isNonNullable(t)&&3e3!==t)return t},ls=(e,t,s)=>{const i=8*s;return i/(i/e+t)};class ps{throughput;rtt;subscription=new e.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(t){this.tuningConfig=t;const s=ps.load('one_video_throughput')||(t.useBrowserEstimation?hs():void 0)||5e3,i=ps.load('one_video_rtt')??(t.useBrowserEstimation?cs():void 0)??0;if(this.throughput$=new e.ValueSubject(s),this.rtt$=new e.ValueSubject(i),this.rttAdjustedThroughput$=new e.ValueSubject(ls(s,i,t.rttPenaltyRequestSize)),this.throughput=new is({initial:s,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:-1,deviationDepth:t.deviationDepth,deviationFactor:t.deviationFactor,label:'throughput'}),this.rtt=new is({initial:i,emaAlphaSlow:t.emaAlphaSlow,emaAlphaFast:t.emaAlphaFast,changeThreshold:t.changeThreshold,fastDirection:1,deviationDepth:t.deviationDepth,deviationFactor:t.deviationFactor,label:'rtt'}),t.useBrowserEstimation){const t=()=>{const t=hs();t&&this.throughput.next(t);const s=cs();e.isNonNullable(s)&&this.rtt.next(s)};us&&'onchange'in us&&this.subscription.add(e.fromEvent(us,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((e=>{ds('one_video_throughput',e.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((e=>{ds('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})=>ls(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.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(t){let s=0,i=e.now();const a=new e.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(t),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,1)}this.concurrentDownloads.delete(t),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=>{this.concurrentDownloads.delete(t),s.releaseLock(),t.cancel(`Throughput Estimator error: ${e}`).catch((()=>{}))},d=async({done:u,value:h})=>{u?(this.addRawSpeed(i,e.now()-a,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,r+=h.byteLength,r>=this.tuningConfig.streamMinSampleSize&&e.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,e.now()-o,this.concurrentDownloads.size),r=0,o=e.now()),await(s?.read().then(d,n)))};this.concurrentDownloads.add(t),s?.read().then(d,n)}addRawSpeed(e,t,s=1){if(ps.sanityCheck(e,t)){const i=8*e/t;this.throughput.next(i*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(os){case as.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case as.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case as.RUNTIME:return rs.get(t);default:e.assertNever(os)}})(t);if(e.isNonNullable(s))return parseInt(s,10)??void 0}}const ms={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}};const fs=({playbackState:t,seekState:s,playbackAbort$:i,looped$:a,position$:r})=>new e.Observable((o=>{let n;const d=t.transitionEnded$.pipe(e.filter((e=>(e.from===exports.PlaybackState.PAUSED||e.from===exports.PlaybackState.STOPPED)&&e.to===exports.PlaybackState.PLAYING))),u=t.stateChangeEnded$.pipe(e.filter((e=>e.from===exports.PlaybackState.PLAYING&&e.to===exports.PlaybackState.PAUSED))),c=s.stateChangeEnded$.pipe(e.filter((({to:e})=>e.state===h.Requested&&(t.getTransition()?.from??t.getState())===exports.PlaybackState.PLAYING))),l=s.stateChangeEnded$.pipe(e.filter((({from:e,to:s})=>e.state===h.Applying&&s.state===h.None&&(t.getTransition()?.from??t.getState())===exports.PlaybackState.PLAYING))),p=e.merge(d,l).pipe(e.map((()=>r.getValue())),e.filter(e.isNonNullable)),m=e.merge(e.merge(u,c,i),a).pipe(e.map((()=>r.getValue())),e.filter(e.isNonNullable));return(new e.Subscription).add(p.subscribe((e=>{n=e}))).add(m.subscribe((t=>{if(e.isNullable(n)||n===t)return;const s={from:n,to:t};n=void 0,o.next(s)})))})),Ss={[o.SCREEN]:{vod:[...Gt?[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:[],exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,...Gt?[]:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND],exports.VideoFormat.MPEG],live:Gt?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return 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;initedAt;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),playbackRate: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({}),currentPlaybackRate$:new e.ValueSubject(1),currentBuffer$:new e.ValueSubject({start:0,end: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={inited$:new e.Subject,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,canplay$:new e.Subject,log$:new e.Subject};experimental={element$:new e.ValueSubject(void 0),enableDebugTelemetry$:new e.ValueSubject(!1),dumpTelemetry:se};constructor(e={}){if(this.initLogs(),this.tuning=(e=>{const t={};for(const s of Object.keys(ms)){const i=ms[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 ps(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 ts({screenFormatsPriority:[...Ss[o.SCREEN].live,...Ss[o.SCREEN].vod],chromecastFormatsPriority:[...Ss[o.CHROMECAST].live,...Ss[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,!1),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}setPlaybackRate(t){e.assertNonNullable(this.providerContainer);const s=this.providerContainer?.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(t),s.playbackRate=t),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.playbackRate.stateChangeEnded$.pipe(e.map((e=>e.to))).subscribe(this.info.currentPlaybackRate$)).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)),e.filter((()=>!this.isPlaybackStarted))).subscribe((()=>{this.initedAt=e.now(),this.events.inited$.next(),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$.pipe(e.map((e=>e?{start:e.from,end:e.to}:{start:0,end:0}))).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$.pipe(e.once(),e.map((()=>e.now()-this.initedAt))).subscribe(this.events.firstBytes$)).add(t.providerOutput.firstFrameEvent$.pipe(e.once(),e.map((()=>e.now()-this.initedAt))).subscribe(this.events.firstFrame$)).add(t.providerOutput.canplay$.pipe(e.once(),e.map((()=>e.now()-this.initedAt))).subscribe(this.events.canplay$)).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:{const t=new e.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe((e=>t.next(e&&Math.floor(e/1e3))))),o.add(fs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:t}).pipe(e.map((({from:e,to:t})=>({start:e,end:t})))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(fs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).pipe(e.map((({from:e,to:t})=>({start:e,end:t})))).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(),playbackRate:this.info.currentPlaybackRate$.getValue(),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),te={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((e=>{ee=e})),this.providerContainer.current$.subscribe((({type:e})=>ie('provider',e))),t.duration$.subscribe((e=>ie('duration',e))),t.availableVideoTracks$.pipe(e.filter((e=>!!e.length)),e.once()).subscribe((e=>ie('tracks',e))),this.events.fatalError$.subscribe(new ae('fatalError')),this.events.managedError$.subscribe(new ae('managedError')),t.position$.subscribe(new ae('position')),t.currentVideoTrack$.pipe(e.map((e=>e?.quality))).subscribe(new ae('quality')),this.info.currentBuffer$.subscribe(new ae('buffer')),t.isBuffering$.subscribe(new ae('isBuffering'))].forEach((e=>this.subscription.add(e))),ie('codecs',Object.keys(qt).filter((e=>qt[e])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.75-beta.0';