@vkontakte/videoplayer-core 2.0.86-dev.f2e1ec4.0 → 2.0.86
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- package/index.d.ts +8 -57
- package/package.json +2 -2
package/esnext.cjs.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.86
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.86
|
|
3
|
+
* Thu, 11 May 2023 16:24:35 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-86/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Ds=Object.create;var It=Object.defineProperty;var Ns=Object.getOwnPropertyDescriptor;var Rs=Object.getOwnPropertyNames;var _s=Object.getPrototypeOf,Cs=Object.prototype.hasOwnProperty;var Is=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Rs(e))!Cs.call(r,i)&&i!==t&&It(r,i,{get:()=>e[i],enumerable:!(s=Ns(e,i))||s.enumerable});return r};var Lt=(r,e,t)=>(t=r!=null?Ds(_s(r)):{},Is(e||!r||!r.__esModule?It(t,"default",{value:r,enumerable:!0}):t,r));var a=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),Ls=require("lodash/debounce.js");const xs="2.0.86-dev.f2e1ec4.0",Bs="esnext.cjs.js";exports.PlaybackState=void 0;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(r){r.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_CMAF="DASH_LIVE_CMAF",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.HLS_LIVE_CMAF="HLS_LIVE_CMAF",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var re;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(re||(re={}));exports.ChromecastState=void 0;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var N;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(N||(N={}));exports.Surface=void 0;(function(r){r.NONE="none",r.INLINE="inline",r.FULLSCREEN="fullscreen",r.SECOND_SCREEN="second_screen",r.PIP="pip"})(exports.Surface||(exports.Surface={}));var Vs=r=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",r),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Os{connection$=new a.ValueSubject(void 0);castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new a.Subject;contentId;realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new a.Subscription;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const s=a.isNonNullable(window.chrome?.cast),i=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Vs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,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(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=s.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 a.assertNever(i.sessionState)}})).add(a.merge(a.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),a.map(i=>i.castState)),a.observableFrom([s.getCastState()])).pipe(a.filterChanged(),a.map(Ms),a.tap(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{const n=i===exports.ChromecastState.CONNECTED,o=a.isNonNullable(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();a.assertNonNullable(u);const d=u.getCastDevice(),c=u.getMediaSession()?.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:i)}))}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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(i){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const Ms=r=>{switch(r){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 a.assertNever(r)}};var qe;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(qe||(qe={}));var Ye=(r,e=0,t=qe.OFFSET_P)=>{switch(t){case qe.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case qe.PLAYBACK_SHIFT:{if(e===0)return r;const s=new URL(r);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:a.assertNever(t)}return r},T=(r,e,t=!1)=>{const s=r.getTransition();(t||!s||s.to===e)&&r.setState(e)};exports.VideoQuality=void 0;(function(r){r.INVARIANT="Invariant quality",r.Q_144P="144p",r.Q_240P="240p",r.Q_360P="360p",r.Q_480P="480p",r.Q_720P="720p",r.Q_1080P="1080p",r.Q_1440P="1440p",r.Q_2160P="2160p",r.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const le={[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}},ft=(r,e)=>le[r].height>le[e].height,Fs=(r,e)=>le[r].height>=le[e].height,tt=(r,e)=>le[r].height<le[e].height,Us=(r,e)=>le[r].height<=le[e].height,Hs=r=>r.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:tt(e,t)?1:-1)[0],qs=Object.keys(le).sort((r,e)=>tt(r,e)?-1:1),Oe=({width:r,height:e})=>{const t=Math.min(r,e),s=Math.max(r,e);return qs.find(i=>{const n=le[i];return n.width>=s&&n.height>=t})},Ys=r=>le[r].height,mt=r=>r===exports.VideoQuality.INVARIANT;class G{state;transition;transitionStarted$=new a.Subject;transitionEnded$=new a.Subject;transitionUpdated$=new a.Subject;forceChanged$=new a.Subject;stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=a.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(e){const t=this.transition,s=this.state;s===e||a.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const js=r=>{switch(r){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.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(r)}};var D;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(D||(D={}));const Gs=5,zs=5,Qs=500,xt=7e3;class Ws{subscription=new a.Subscription;loadMediaTimeoutSubscription=new a.Subscription;videoState=new G(D.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(js(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(a.map(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));const t=(i,n)=>this.subscription.add(i.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new a.Subject;e.add(i.pipe(a.debounce(Qs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const u=o.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state===N.Applying||Math.abs(u-n)>Gs)&&i.next(u),n=u})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);const{remotePlayer:n}=this.params.connection,o=i.value,u=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(u!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<zs&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});const s=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(s,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(D.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(D.PLAYING),T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:N.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===D.PAUSED||e===D.PLAYING)&&(this.videoState.setState(D.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===D.PLAYING||e===D.PAUSED)&&(this.videoState.setState(D.PLAYING),T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===D.READY&&this.videoState.setState(D.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&T(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==D.STOPPED&&this.videoState.setState(D.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(e){const t=this.params.source;let s,i,n;switch(e){case exports.VideoFormat.MPEG:{const c=t[e];a.assertNonNullable(c);const l=Hs(Object.keys(c));a.assertNonNullable(l);const h=c[l];a.assertNonNullable(h),s=h,i="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=t[e];a.assertNonNullable(c),s=c.url,i="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=t[e];a.assertNonNullable(c),s=c.url,i="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=t[e];a.assertNonNullable(c),s=c.url,i="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=t[e];a.assertNonNullable(c),s=Ye(c.url),i="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:l}),l}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??s,i);o.contentUrl=s,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return a.isNonNullable(u)&&(o.metadata.title=u),a.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===N.Applying||s.state===N.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((i,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(xt).subscribe(()=>n(`timeout(${xt})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:i})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(n)};`}),s===exports.PlaybackState.STOPPED){e!==D.STOPPED&&(this.videoState.startTransitionTo(D.STOPPED),this.stop());return}if(!t){if(i?.to!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&e!==D.STOPPED){this.seek(n.position/1e3);return}switch(s){case exports.PlaybackState.READY:{switch(e){case D.PLAYING:case D.PAUSED:case D.READY:break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:a.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case D.PLAYING:break;case D.PAUSED:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.READY:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:a.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case D.PLAYING:this.videoState.startTransitionTo(D.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case D.PAUSED:break;case D.READY:this.videoState.startTransitionTo(D.PAUSED),this.videoState.setState(D.PAUSED);break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:a.assertNever(e)}break}default:a.assertNever(s)}}}}class Bt{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 i=0,n=s.length;i<n;i++)if(s[i].callback===t){s.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let i=0,n=s.length;i<n;i++){const o=s[i];try{o.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class ns extends Bt{constructor(){super(),this.listeners||Bt.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let os=class{constructor(){Object.defineProperty(this,"signal",{value:new ns,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(os.prototype[Symbol.toStringTag]="AbortController",ns.prototype[Symbol.toStringTag]="AbortSignal");function us(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Js(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=r;if(!us({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||i)&&(n=function(c,l){let h;l&&l.signal&&(h=l.signal,delete l.signal);const f=new t(c,l);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,c)=>{const l=n&&n.prototype.isPrototypeOf(d)?d.signal:c?c.signal:void 0;if(l){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(l.aborted)return Promise.reject(h);const f=new Promise((m,p)=>{l.addEventListener("abort",()=>p(h),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([f,o(d,c)])}return o(d,c)},Request:n}}const vt=us({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cs=vt?Js({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,je=vt?cs.fetch:window.fetch;vt?cs.Request:window.Request;const Ve=vt?os:window.AbortController,Xe=r=>r.range?r.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class st{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[n,o]=Xe(i.request);if(n>=s.from&&o<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const i=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,i)}}}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:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(Xe),i=s[0][0];let n=s[0][1];for(let f=1;f<s.length&&n<this.params.minDataSize;f++){const m=s[f][1];m-i<=2*this.params.minDataSize&&(n=Math.max(n,m))}i===0?n=Math.max(n,i+this.params.minInitSize):n=Math.max(n,i+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${i}-${n}`);const u=o.toString(),d=new Ve,c=d.signal,l={url:e,from:i,to:n,loaded:0,data:null,abortController:d};c.addEventListener("abort",()=>this.onBigRequestAbort(l));const h=f=>{throw this.params.onError?.({id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return je(u,{signal:c}).then(f=>{if(l.response=f,!f.ok||!f.body){this.onBigRequestError(l);return}const[m,p]=f.body.tee();this.params.onDownloadStream?.(p);const g=m.getReader(),E=parseInt(f.headers.get("Content-Length")??"",10)||n-i+1;l.data=new ArrayBuffer(E);const S=new Uint8Array(l.data),v=async({done:A,value:k})=>{A?this.onBigRequestProgress(l):k&&(S.set(k,l.loaded),l.loaded+=k.byteLength,this.onBigRequestProgress(l),await g?.read().then(v,st.suppressStreamErrors).catch(h))};g?.read().then(v,st.suppressStreamErrors).catch(h)},st.suppressAbort).catch(f=>this.onBigRequestError(l,f)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:n,response:o}){if(!this.activeRequests.has(e)||!n)return;const u=this.dashJsRequestQueue.get(e)??[];for(const d of u){const{request:c}=d,[l,h]=Xe(c),f=l>=t&&h<=t+i,m=t>=l&&t+i<h,p=n.slice(l-t,Math.min(h-t+1,i));if((f||m)&&(c.requestStartDate=c.requestStartDate??new Date,c.firstByteDate=c.firstByteDate??new Date,c.bytesLoaded=p.byteLength,c.bytesTotal=s-t),f){c.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(E=>E!==d)),d.success?.(p,"",e);const g=o?Array.from(o.headers.entries()).map(([E,S])=>`${E}: ${S}`).join(`\r
|
|
7
|
-
`):"";this.dashMetrics?.addHttpRequest(c,e,o?.status??200,g,[])}else m&&d.progress?.({loaded:i,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},i){if(this.params.onError?.({id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:i}),!this.activeRequests.has(e))return;const n=this.dashJsRequestQueue.get(e)??[];for(const o of n){const[u,d]=Xe(o.request);(u>=t&&u<s||d>t&&d<=s)&&o?.error?.(o.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 n of i){const[o,u]=Xe(n.request);(o>=t&&o<s||u>t&&u<=s)&&n?.abort?.(n.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class St{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(St.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;St.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Ks=(r,e)=>t=>({create:s=>{const i=r(t).create(s);return new St(i,e,s)}}),Xs=(r,e)=>{const t=new st(e);return r.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:n=>{const o=i(n);return Ks(o,t)}}},!0),()=>t.destroy()};var Zs=r=>{let e,t=!1,s=!1;r.on("playbackTimeUpdated",({timeToEnd:i})=>{s=i<=3,t&&s&&e?.()}),r.extend("MediaSourceController",function(){const{parent:i}=this,n=i.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&s&&e?.()}}},!0)},ei=r=>{const e=new a.ValueSubject(1/0),t=new a.Subject,s=new a.ValueSubject(void 0),i=new a.ValueSubject(void 0);let n=NaN,o=!1;const u=()=>{n=Date.now(),o=!1},d=l=>{const h=Object.fromEntries(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(p=>p.split(": ")));if("x-playback-duration"in h||"x-playback-duration-millis"in h){const p=parseInt(l.getResponseHeader("X-Playback-Duration")??"",10),E=parseInt(l.getResponseHeader("X-Playback-Duration-Millis")??"",10)??p*1e3??NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const f=h["x-delivery-type"]??exports.HttpConnectionType.HTTP1,m={1:!0,0:!1}[h["x-reused"]]??void 0;s.next(f),i.next(m)},c=l=>{l.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return r.extend("XHRLoader",function(){const{parent:l}=this,h=l.load.bind(l);return{load:function(f){if(f.request.type==="MPD"){const m=f.onload,p=f.progress;f.onload=function(...g){return d(this),m(...g)},f.progress=function(...g){return c(this),p(...g)},u()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:i,connectionType$:s}},Ge=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},ti=r=>r.extend("RequestModifier",()=>({modifyRequestURL:Ge}),!0),si=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[i,n]=s.request.range.split("-").map(u=>parseInt(u,10)),o=new URL(s.request.url,location.href);o.searchParams.append("bytes",`${i}-${n}`),s.request.url=o.toString(),s.request.range=void 0}t(s)}}},!0)};const pe=(r,e,t,{equal:s=(o,u)=>o===u,changed$:i,onError:n}={})=>{const o=r.getState(),u=e(),d=a.isNullable(i),c=new a.Subscription;return i&&c.add(i.subscribe(l=>{const h=r.getState();s(l,h)&&r.setState(l)},n)),s(u,o)||(t(o),d&&r.setState(o)),c.add(r.stateChangeStarted$.subscribe(l=>{t(l.to),d&&r.setState(l.to)},n)),c},Me=(r,e,t)=>pe(e,()=>r.loop,s=>{a.isNonNullable(s)&&(r.loop=s)},{onError:t}),ve=(r,e,t,s)=>pe(e,()=>({muted:r.muted,volume:r.volume}),i=>{a.isNonNullable(i)&&(r.muted=i.muted,r.volume=i.volume)},{equal:(i,n)=>i===n||i?.muted===n?.muted&&i?.volume===n?.volume,changed$:t,onError:s}),Ce=(r,e,t,s)=>pe(e,()=>r.playbackRate,i=>{a.isNonNullable(i)&&(r.playbackRate=i)},{changed$:t,onError:s}),ii=r=>["__",r.language,r.label].join("|"),ai=(r,e)=>{if(r.id===e)return!0;const[t,s,i]=e.split("|");return r.language===s&&r.label===i};class me{available$=new a.Subject;current$=new a.ValueSubject(void 0);error$=new a.Subject;video;cueSettings;subscription=new a.Subscription;externalTracks=new Map;connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const i=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(pe(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:i})),this.subscription.add(pe(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:i})),this.subscription.add(pe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),a.filterChanged((s,i)=>s.length===i.length&&s.every(({id:n},o)=>n===i[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),a.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),a.filterChanged()).subscribe(this.current$));const t=s=>this.applyCueSettings(s.target?.activeCues??null);this.subscription.add(a.fromEvent(e,"addtrack").subscribe(s=>{s.track?.addEventListener("cuechange",t);const i=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",i))};s.track?.addEventListener("cuechange",i)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(s=>{s.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const i=s;a.isNonNullable(t.align)&&(i.align=t.align),a.isNonNullable(t.position)&&(i.position=t.position),a.isNonNullable(t.size)&&(i.size=t.size),a.isNonNullable(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(me.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=e.id!==""?e.id:ii(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!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&ai(t,e)?t.mode="showing":t.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(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ke=r=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r.appendChild(e),e};class Nt{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(){this.pauseTimestamp===0&&(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}}const ds=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Vt=r=>{const e=ds(r);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===r)},ri=r=>{const e=ds(r);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};var ls=()=>{const{userAgent:r}=window.navigator;return!/chrome/i.test(r)&&/webkit|safari|khtml/i.test(r)};const Pt=3;class ni{_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 i=this._source.buffered.start(t);const n=this._source.buffered.end(t);i>e&&i-e<Pt&&(i=e),this._buffer.push({from:i,to:n,i:t})}return this._buffer.sort(function(t,s){return t.from-s.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||Pt))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:n})=>{const o=i>=e&&i<t,u=n>=e&&n<t;o&&u||(o?s(t,n):u?s(i,e):i<e&&n>t?(s(t,n),s(i,e)):s(i,n))})}destroy(){this._buffer=[]}}var hs=(r,e,t=Pt)=>{let s=0,i=0;for(let n=0;n<r.length;n++){const o=r.start(n),u=r.end(n);if(o<=e&&e<=u){if(s=o,i=u,!t)return{from:s,to:i};for(let d=n-1;d>=0;d--)r.end(d)+t>=s&&(s=r.start(d));for(let d=n+1;d<r.length;d++)r.start(d)-t<=i&&(i=r.end(d))}}return{from:s,to:i}};const oi=50,ui=r=>r.webkitAudioDecodedByteCount!==void 0?!!r.webkitAudioDecodedByteCount:r.mozHasAudio!==void 0?r.mozHasAudio:r.audioTracks?!!r.audioTracks.length:!0,$e=r=>{const e=A=>a.fromEvent(r,A).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=a.merge(...t.map(A=>a.fromEvent(r,A))).pipe(a.map(A=>A.type==="ended"?r.readyState<2:r.readyState<3),a.filterChanged()),i=a.merge(a.fromEvent(r,"progress"),a.fromEvent(r,"timeupdate")).pipe(a.map(()=>hs(r.buffered,r.currentTime))),n=ls()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(r,"playing").pipe(a.debounce(oi),a.map(()=>ui(r))),u=a.fromEvent(r,"volumechange").pipe(a.map(()=>({muted:r.muted,volume:r.volume}))),d=a.fromEvent(r,"ratechange").pipe(a.map(()=>r.playbackRate)),c=a.fromEvent(r,"error").pipe(a.filter(()=>Boolean(r.error||r.played.length)),a.map(()=>{const A=r.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=a.fromEvent(r,"timeupdate").pipe(a.map(()=>r.currentTime)),h=new a.Subject,f=.3;let m;l.subscribe(A=>{r.loop&&a.isNonNullable(m)&&a.isNonNullable(A)&&m>=r.duration-f&&A<=f&&h.next(m),m=A});const p=a.fromEvent(r,"enterpictureinpicture"),g=a.fromEvent(r,"leavepictureinpicture"),E=new a.ValueSubject(ri(r));p.subscribe(()=>E.next(!0)),g.subscribe(()=>E.next(!1));const S=new a.ValueSubject(Vt(r));return a.fromEvent(r,"fullscreenchange").pipe(a.map(()=>Vt(r))).subscribe(S),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:a.fromEvent(r,"durationchange").pipe(a.map(()=>r.duration)),isBuffering$:s,currentBuffer$:i,volumeState$:u,isAudioAvailable$:o,playbackRateState$:d,inPiP$:E,inFullscreen$:S}},Rt=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let _t=!1,Ee={};const ci=r=>{_t=r},di=()=>{Ee={}},li=r=>{r(Ee)},ct=(r,e)=>{_t&&(Ee.meta=Ee.meta??{},Ee.meta[r]=e)};class fe{name;constructor(e){this.name=e}next(e){if(!_t)return;Ee.series=Ee.series??{};const t=Ee.series[this.name]??[];t.push([Date.now(),e]),Ee.series[this.name]=t}}const hi=new fe("best_bitrate"),fi=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class pi{last;history={};recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const rt=(r,{container:e,throughput:t,tuning:s,limits:i,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:c})=>{const l=s.usePixelRatio?window.devicePixelRatio??1:1,h=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*s.containerSizeFactor,height:e.height*l*s.containerSizeFactor},f=h&&Oe(h),m=s.considerPlaybackRate&&a.isNonNullable(u)?u:1,p=r.filter(C=>!mt(C.quality)).sort((C,U)=>ft(C.quality,U.quality)?-1:1),g=p.at(-1)?.quality,E=p.at(0)?.quality,S=a.isNullable(i)||a.isNonNullable(i.min)&&a.isNonNullable(i.max)&&tt(i.max,i.min)||a.isNonNullable(i.min)&&E&&ft(i.min,E)||a.isNonNullable(i.max)&&g&&tt(i.max,g),v=m*fi(o??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),k=p.filter(C=>{const U=f?tt(C.quality,f):!0,I=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(C.bitrate)?t-n>=C.bitrate*v:!0,M=s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!mt(d.quality)&&(o??0)<s.minBufferToSwitchUp&&ft(C.quality,d.quality),j=S||(a.isNullable(i.max)||Us(C.quality,i.max))&&(a.isNullable(i.min)||Fs(C.quality,i.min));return U&&I&&!M&&j})[0];k&&k.bitrate&&hi.next(k.bitrate);const y=k??p[Math.ceil((p.length-1)/2)]??r[0],P=y&&c&&c.history[y.id]&&a.now()-c.history[y.id]<=s.trackCooldown&&(!c.last||y.id!==c.last.id);if(y?.id&&c&&!P&&c.recordSelection(y),P&&c?.last){const C=c.last;return c?.recordSwitch(C),C}return c?.recordSwitch(y),y};var ae=r=>new URL(r).hostname;const mi=300,bt=(r,e=mi)=>new a.Observable(t=>{const{width:s,height:i}=r.getBoundingClientRect();if(t.next({width:s,height:i}),!window.ResizeObserver)return;const n=new ResizeObserver(Ls(o=>{const u=o[0];if(!u)return;let d,c;u.contentBoxSize&&u.contentBoxSize[0]?(c=u.contentBoxSize[0].blockSize,d=u.contentBoxSize[0].inlineSize):u.contentRect&&(d=u.contentRect.width,c=u.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(c)&&t.next({width:d,height:c})},e));return n.observe(r),()=>n.disconnect()}),Ae=r=>{try{r.pause(),r.playbackRate=0,r.removeAttribute("src"),r.load(),r.remove()}catch(e){console.error(e)}},Si=5e3,Ze={};var R;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(R||(R={}));const K=(r,e)=>new a.Observable(t=>{const s=i=>t.next(i);return r.on(e,s),()=>r.off(e,s)});class Ot{subscription=new a.Subscription;videoState=new G(R.DOWNLOADING_LIB);video;player;params;textTracksManager=new me;videoTracks=[];frameRatesByFrameHeight={};isLive$=new a.ValueSubject(void 0);maxSeekBackTime$=new a.ValueSubject(1/0);availableFrom$=new a.ValueSubject(void 0);elementSize$=new a.ValueSubject(void 0);liveOffset=new Nt;destroyBigRequest;constructor(e){this.video=ke(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${i?.toString?.()}`,thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),Si);import("dashjs/dist/dash.mediaplayer.min.js").then(i=>{e||(Ze.MediaPlayer=i.MediaPlayer,Ze.Debug=i.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(Ze.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Ze.Debug,"dashjs not loaded"),this.player=Ze.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Rt(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Xs(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&si(this.player),Zs(this.player),this.params.tuning.requestQuick&&ti(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(R.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=S=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:S})},i=(S,v)=>this.subscription.add(S.subscribe(v,s));i(bt(this.video),this.elementSize$),i(K(this.player,"error").pipe(a.map(S=>{const v=typeof S.error=="object"?S.error.code:S.error,A=typeof S.error=="object"?S.error.message:void 0;return{id:`DashJS#${v}`,message:A}})),e.error$),i(K(this.player,"playbackError").pipe(a.map(S=>({id:"DashJSPlayback",message:S.error}))),e.error$);const n=K(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:S})=>S==="video"),a.map(({newQuality:S})=>this.videoTracks.find(({bitrateInfo:v})=>v.qualityIndex===S)?.track));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:S})=>S===R.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(pe(t.videoTrack,()=>{const S=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:v})=>v.qualityIndex===S)?.track?.id},S=>{if(a.isNullable(S))return;const v=this.videoTracks.find(({track:A})=>A.id===S)?.bitrateInfo;v&&this.player.setQualityFor("video",v.qualityIndex)},{changed$:n.pipe(a.map(S=>S?.id)),onError:s}))},s)),this.subscription.add(pe(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,S=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:S}}}}),{onError:s})),i(K(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:S})=>S==="video"),a.map(({state:S})=>S==="bufferStalled")),e.isBuffering$),i(K(this.player,"fragmentLoadingStarted"),({mediaType:S,request:{url:v}})=>{const A=this.player.getDashMetrics(),k=A.getLatestFragmentRequestHeaderValueByID(S,"X-Reused"),y=A.getLatestFragmentRequestHeaderValueByID(S,"X-Delivery-Type")??exports.HttpConnectionType.HTTP1,P={1:!0,0:!1}[k]??void 0;this.params.output.httpConnectionType$.next(y),this.params.output.httpConnectionReused$.next(P),e.hostname$.next(ae(v))}),i(K(this.player,"streamInitialized"),({streamInfo:{duration:S,manifestInfo:{isDynamic:v,availableFrom:A}}})=>{this.isLive$.next(v),this.availableFrom$.next(A.getTime()),v||e.duration$.next(S),this.videoTracks=[];const k=this.player.getQualityFor("video");let y;for(const P of this.player.getBitrateInfoListFor("video")){const C=P.qualityIndex.toString(10),U=Oe(P),I=P.bitrate/1e3,M={width:P.width,height:P.height},j=this.frameRatesByFrameHeight[P.height];if(U){const B={id:C,quality:U,bitrate:I,size:M,fps:j};this.videoTracks.push({track:B,bitrateInfo:P}),P.qualityIndex===k&&(y=B)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:P})=>P)),y&&e.currentVideoTrack$.next(y),this.videoState.setState(R.STREAM_INITIALIZED),this.videoState.startTransitionTo(R.READY)}),i(K(this.player,"fragmentLoadingCompleted"),({request:S})=>{if(!S.requestEndDate||!S.firstByteDate||!S.bytesLoaded)return;const v=S.requestEndDate.getTime()-S.firstByteDate.getTime(),A=S.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(A,v)}),i(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const S=this.params.dependencies.throughputEstimator.throughput$.getValue(),v=rt(this.videoTracks.map(({track:k})=>k),{container:this.elementSize$.getValue(),throughput:S,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),A=this.videoTracks.find(({track:k})=>k===v);A?.bitrateInfo&&this.player.setQualityFor("video",A?.bitrateInfo.qualityIndex,!1)}),i(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:S})=>S),a.map(({maxSeekBackTime:S})=>-S/1e3)),this.params.output.duration$);const o=K(this.player,"playbackTimeUpdated").pipe(a.map(({time:S})=>S??0));i(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:S,currentTime:v})=>this.params.output.liveTime$.next(S+v*1e3)),i(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),i(K(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),i(K(this.player,"playbackEnded"),e.endedEvent$),i(K(this.player,"playbackProgress").pipe(a.map(()=>hs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),i(K(this.player,"playbackPlaying"),()=>{this.videoState.setState(R.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)}),i(K(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(R.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),i(K(this.player,"playbackPaused"),()=>{this.videoState.setState(R.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)}),i(K(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===R.READY&&this.videoState.setState(R.READY)}),i(this.isLive$,e.isLive$),i(bt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const u=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));i(u,this.syncPlayback);const{playbackDuration$:d,ping$:c,connectionType$:l,connectionReused$:h}=ei(this.player);i(l,this.params.output.httpConnectionType$),i(h,this.params.output.httpConnectionReused$),i(d,this.maxSeekBackTime$),i(c.pipe(a.once()),e.firstBytesEvent$),i(K(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&i(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(S=>S<60))}),({isLive:S,isShort:v})=>{const A=!S&&v;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:A}}})}),i(o.pipe(a.filter(S=>S>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(K(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(K(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(Me(this.video,t.isLooped,s));const{volumeState$:f,looped$:m,playbackRateState$:p,inPiP$:g,inFullscreen$:E}=$e(this.video);this.subscription.add(ve(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(m.subscribe(e.loopedEvent$)),this.subscription.add(Ce(this.video,t.playbackRate,p,s)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(E.subscribe(e.inFullscreen$))}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(R.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(R.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=Ye(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,qe.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(R.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(R.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===R.DOWNLOADING_LIB||e===R.STREAM_INITIALIZED))switch(s?.to!==exports.PlaybackState.PAUSED&&i.state===N.Requested&&e!==R.STOPPED&&t!==exports.PlaybackState.STOPPED&&(n?this.seek(i.position-this.liveOffset.getTotalPausedTime()):this.seek(i.position)),t){case exports.PlaybackState.STOPPED:{switch(e){case R.STOPPED:break;case R.PLAYING:case R.PAUSED:case R.READY:this.stop();break;default:a.assertNever(e)}break}case exports.PlaybackState.READY:{switch(e){case R.STOPPED:this.prepare();break;case R.PLAYING:case R.PAUSED:case R.READY:break;default:a.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case R.PLAYING:break;case R.PAUSED:n&&(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 R.READY:this.play();break;case R.STOPPED:this.prepare();break;default:a.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case R.PLAYING:this.pause(),this.liveOffset.pause();break;case R.PAUSED:break;case R.READY:this.videoState.setState(R.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case R.STOPPED:this.prepare();break;default:a.assertNever(e)}break}default:a.assertNever(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch{}Ae(this.video),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var nt=r=>{switch(r){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}};const Mt=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Ie=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!Mt(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(s){return Mt(s)&&(r.muted=!1,console.warn(s)),!1}}return!0};function se(){return a.now()}function fs(r){return se()-r}function Ft(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,i=o=>s.test(o);return{resolve:(o,u,d=!1)=>{i(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let c=o.indexOf("?")>-1?"&":"?";return d&&(o+=c+"lowLat=1",c="&"),u&&(o+=c+"_rnd="+Math.floor(999999999*Math.random())),o}}}function bi(r,e,t){const s=(...i)=>{t.apply(null,i),r.removeEventListener(e,s)};r.addEventListener(e,s)}function pt(r,e,t,s){const i=window.XMLHttpRequest;let n,o,u,d=!1,c=0,l,h,f=!1,m="arraybuffer",p=7e3,g=2e3,E=()=>{if(d)return;a.assertNonNullable(l);const B=fs(l);let J;if(B<g){J=g-B,setTimeout(E,J);return}g*=2,g>p&&(g=p),o&&o.abort(),o=new i,P()};const S=B=>(n=B,j),v=B=>(h=B,j),A=()=>(m="json",j),k=()=>{if(!d){if(--c>=0){E(),s&&s();return}d=!0,h&&h(),t&&t()}},y=B=>(f=B,j),P=()=>{l=se(),o=new i,o.open("get",r);let B=0,J,he=0;const Pe=()=>(a.assertNonNullable(l),Math.max(l,Math.max(J||0,he||0)));if(n&&o.addEventListener("progress",w=>{const F=se();n.updateChunk&&w.loaded>B&&(n.updateChunk(Pe(),w.loaded-B),B=w.loaded,J=F)}),u&&(o.timeout=u,o.addEventListener("timeout",()=>k())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const w=o.status;if(w>=200&&w<300){if(o.response.byteLength&&n){const F=o.response.byteLength-B;F&&n.updateChunk&&n.updateChunk(Pe(),F)}h&&h(),o&&e(o.response)}else k()}),o.addEventListener("error",()=>{k()}),f){const w=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(he=se(),o.removeEventListener("readystatechange",w))};o.addEventListener("readystatechange",w)}return o.responseType=m,o.send(),j},j={withBitrateReporting:S,withParallel:y,withJSONResponse:A,withRetryCount:B=>(c=B,j),withRetryInterval:(B,J)=>(a.isNonNullable(B)&&(g=B),a.isNonNullable(J)&&(p=J),j),withTimeout:B=>(u=B,j),withFinally:v,send:P,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return j}const gi=100,yi=2e3,Ei=500;let Ti=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),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):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-Ei;if(t-e>yi){let s=0,i=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,i+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,u=n.end-n.start;s+=o;const d=n.bytes*o/u;i+=d,n.start=t,n.bytes-=d}}}if(i>0&&s>0){const n=i*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/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>gi&&(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 vi{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,this.logger=n}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=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=se()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pt(t,n,()=>i("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),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):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_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 n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=i,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=i,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}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}}const dt=1e4,lt=3,ki=300,$i=2e3,Ai=6e4,Pi=10,wi=1,Di=500;class Ni{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 Ti(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ft(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){this._switchToQuality(t);return}}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=Ft(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 s!==0&&(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",()=>{Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):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;s!==0&&(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,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u)n=this.manifest[u],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!i||n.bitrate>i.bitrate)&&(i=n):(!s||s.bitrate>n.bitrate)&&(s=n));return i||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:i,playerCallback:n}=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 o=()=>{bi(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new vi(lt,dt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:i}=this.params;let n=!1,o=null,u=null,d=null,c=null,l=!1;const h=()=>{const k=n&&(!l||l===this.rep);return k||t("Not running!"),k},f=(k,y,P)=>{d&&d.abort(),d=pt(this.urlResolver.resolve(k,!1),y,P,()=>this._retryCallback()).withTimeout(dt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(lt).withFinally(()=>{d=null}).send()},m=(k,y,P)=>{a.assertNonNullable(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),y,P,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},p=k=>{const y=s.playbackRate;s.playbackRate!==k&&(t(`Playback rate switch: ${y}=>${k}`),s.playbackRate=k)},g=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),E()},E=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}const P=se()-1e4;let C=0;for(let I=0;I<this.bufferStates.length;I++){const M=this.bufferStates[I];k=Math.min(k,M.buf),M.ts<P&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${k} drop=${C} jitter=${this.sourceJitter}`);let U=k-wi;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?p(1.15):U>1?p(1.1):U>.3?p(1.05):p(1)}},S=k=>{let y;const P=()=>y&&y.start?y.start.length:0,C=w=>y.start[w]/1e3,U=w=>y.dur[w]/1e3,I=w=>y.fragIndex+w,M=(w,F)=>({chunkIdx:I(w),startTS:C(w),dur:U(w),discontinuity:F}),j=()=>{let w=0;if(y&&y.dur){let F=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=F;this.sourceJitter>1&&(X+=this.sourceJitter-1);let ie=y.dur.length-1;for(;ie>=0&&(X-=y.dur[ie],!(X<=0));--ie);w=Math.min(ie,y.dur.length-1-W),w=Math.max(w,0)}return M(w,!0)},B=w=>{const F=P();if(!(F<=0)){if(a.isNonNullable(w)){for(let W=0;W<F;W++)if(C(W)>w)return M(W)}return j()}},J=w=>{const F=P(),W=w?w.chunkIdx+1:0,X=W-y.fragIndex;if(!(F<=0)){if(!w||X<0||X-F>Pi)return t(`Resync: offset=${X} bChunks=${F} chunk=`+JSON.stringify(w)),j();if(!(X>=F))return M(W-y.fragIndex,!1)}},he=(w,F,W)=>{c&&c.abort(),c=pt(this.urlResolver.resolve(w,!0,this.lowLatency),F,W,()=>this._retryCallback()).withTimeout(dt).withRetryCount(lt).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(w,F)=>{he(k,W=>{if(!h())return;y=W;const X=Boolean(y.lowLatency);X!==this.lowLatency&&g(X);let ie=0;for(let we=0;we<y.dur.length;++we)ie+=y.dur[we];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/y.dur.length)),i({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,w(B(F))},()=>this._handleNetworkError())},nextChunk:J}},v=()=>{n=!1,u&&u.abort(),d&&d.abort(),c&&c.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:k=>{const{videoElement:y,logger:P}=this.params;let C=S(e.jidxUrl),U,I,M,j,B=0,J,he,Pe;const w=()=>{J&&(clearTimeout(J),J=void 0);const L=Math.max(Di,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ee=B+L,Z=se(),te=Math.min(1e4,ee-Z);B=Z;const Se=()=>{c||h()&&C.seek(()=>{h()&&(B=se(),F(),w())})};te>0?J=window.setTimeout(()=>{this.paused?w():Se()},te):Se()},F=()=>{let L;for(;L=C.nextChunk(j);)j=L,Qe(L);const ee=C.nextChunk(M);if(ee){if(M&&ee.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?w():(v(),this._initPlayerWith(e));return}we(ee)}else w()},W=(L,ee)=>{if(!h()||!this.sourceBuffer)return;let Z,te,Se;const be=de=>{window.setTimeout(()=>{h()&&W(L,ee)},de)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),be(100);else{const de=se(),De=y.currentTime;!this.paused&&y.buffered.length>1&&he===De&&de-Pe>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),he!==De&&(he=De,Pe=de);const Ne=this._getBufferSizeSec();if(Ne>30)P(`Buffered ${Ne} seconds; delaying appendBuffer`),be(2e3);else try{this.sourceBuffer.appendBuffer(L),this.videoPlayStarted?(this.bufferStates.push({ts:de,buf:Ne}),E(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ee&&ee()}catch(Re){if(Re.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),Se=this.sourceBuffer.buffered.length,Se!==0&&(Z=this.sourceBuffer.buffered.start(0),te=De,te-Z>4&&this.sourceBuffer.remove(Z,te-3)),be(1e3);else throw Re}}},X=()=>{I&&U&&(P([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(M)]),W(I,function(){I=null,F()}))},ie=L=>e.fragUrlTemplate.replace("%%id%%",L.chunkIdx),we=L=>{h()&&m(ie(L),(ee,Z)=>{if(h()){if(Z/=1e3,I=ee,M=L,o=L.startTS,Z){const te=Math.min(10,L.dur/Z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*te:te}X()}},()=>this._handleNetworkError())},Qe=L=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(L),!1)))},ut=L=>{h()&&(e.cachedHeader=L,W(L,()=>{U=!0,X()}))};n=!0,C.seek(L=>{if(h()){if(B=se(),!L){w();return}j=L,!a.isNullable(k)||L.startTS>k?we(L):(M=L,F())}},k),e.cachedHeader?ut(e.cachedHeader):f(e.headerUrl,ut,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>o},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),a.isNonNullable(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,m,p;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(m=this._getBufferSizeSec(),p=h/this.bitrate,m>10&&p>.8||m>15&&p>.5||m>20&&p>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,m)=>{const p=se();if(this.chunkRateEstimator.addInterval(f,p,m)){const E=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:p-f,speed:E}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,u,d=!0;const c=()=>{let h=n.get();if(h&&u&&this.autoQuality){if(d&&h>u&&fs(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const m=n.updateChunk(h,f);return m&&c(),m},notifySwitch:h=>{const f=se();h<u&&(o=f),u=h}}}_fetchManifest(e,t,s){this.manifestRequest=pt(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(dt).withRetryCount(lt).withRetryInterval(ki,$i).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Ie(t).then(s=>{s||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params,n=o=>{const u=[];return o?.length?(o.forEach((d,c)=>{d.video&&i.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=c,u.push(d))}),u.sort(function(d,c){return d.video&&c.video?c.video.height-d.video.height:c.bitrate-d.bitrate}),u):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(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))},Ai))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var _;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(_||(_={}));const Ri=[_.PAUSED,_.PLAYING,_.READY],_i=[_.PAUSED,_.PLAYING,_.READY];class Ci{subscription=new a.Subscription;video;videoState=new G(_.STOPPED);dash;representations$=new a.ValueSubject([]);textTracksManager=new me;maxSeekBackTime$=new a.ValueSubject(1/0);zeroTime$=new a.ValueSubject(void 0);liveOffset=new Nt;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=i=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(i)}`})}),this.video=ke(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=$e(this.video);this.subscription.add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===_.READY&&this.videoState.setState(_.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(_.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(_.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:i,position:n})=>this.params.output.liveTime$.next(i+n*1e3),t)).add(Me(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:i}})=>{const n=i&&Ys(i);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(i=>{switch(i.to){case _.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case _.MANIFEST_READY:case _.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case _.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case _.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(i.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}createLiveDashPlayer(){const e=new Ni({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,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),i=!s&&a.isNonNullable(t)?t:rt(e.map(({track:o})=>o),{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,n=e.find(({track:o})=>o.id===i)?.representation;a.assertNonNullable(n,"Representations missing"),this.dash.startPlay(n,s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(s)}setVideoTrack(e){const t=this.representations$.getValue().find(({track:s})=>s.id===e)?.representation;a.assertNonNullable(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}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.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(Ye(this.params.source.url,s))}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,s=[];for(const i of t){const n=i.name??i.index.toString(10),o=nt(i.name)??Oe(i.video),u=i.bitrate/1e3,d={...i.video};if(!o)continue;const c={id:n,quality:o,bitrate:u,size:d};s.push({track:c,representation:i})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map(({track:i})=>i)),this.videoState.getTransition()?.to===_.MANIFEST_READY&&this.videoState.setState(_.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,s=this.representations$.getValue().find(({representation:i})=>i===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),a.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case"bandwidth":{const{size:t,duration:s}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,s);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(n)};`}),s===exports.PlaybackState.STOPPED){e!==_.STOPPED&&(this.videoState.startTransitionTo(_.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(_.STOPPED));return}if(!t){if(_i.includes(e)){const o=this.params.desiredState.videoTrack.getTransition()?.to;a.isNonNullable(o)&&this.setVideoTrack(o);const u=this.params.desiredState.autoVideoTrackSwitching.getTransition();u&&this.setAutoQuality(u.to)}if(i?.to!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&Ri.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case _.STOPPED:this.videoState.startTransitionTo(_.MANIFEST_READY),this.dash.attachSource(Ye(this.params.source.url));return;case _.MANIFEST_READY:this.videoState.startTransitionTo(_.READY),this.prepare();break;case _.READY:if(s===exports.PlaybackState.PAUSED)this.videoState.setState(_.PAUSED);else if(s===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(_.PLAYING);const o=i?.from;o&&o===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(_.PAUSED)})}return;case _.PLAYING:s===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(_.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case _.PAUSED:s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(_.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(_.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(e)}}}}var ps=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),s=e===null?exports.HttpConnectionType.HTTP1:e??void 0,i=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:s,reused:i}},Be=(r,e)=>{let t=0;for(let s=0;s<r.length;s++){const i=r.start(s)*1e3,n=r.end(s)*1e3;i<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Ii=r=>{const e=document.createElement("a");return e.href=r,e.origin},Li=r=>{const e=document.createElement("a");return e.href=r,e.host};class ms{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,n,o){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(a.assertNonNullable(this._xhr),this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(s=>s.split(":").map(i=>i.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(Li(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",t,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class gt{_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(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const i=this._sourceBuffer.buffered;let n=0;for(let o=0,u=i.length;o<u;o++)n+=i.end(o)-i.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,n,o,u){this.abort(()=>{let d=0;const c=Date.now();let l=0,h=0,f=0;const m=g=>{i(gt._str2ua(g.substr(d))),d=g.length};let p=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(p=Ge(p)),this._lastXhr=new ms(p,e.failoverHosts,g=>{this._lastXhr=void 0,m(g);const E=Date.now()-c;this._params.onBandwidthChange({size:g.length,duration:E,speed:8*g.length/(E/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),n?.()},g=>{if(g.length-d>u&&m(g),h===0){h=Date.now();return}f=g.length-l;const E=Date.now()-h;f>=100*1024&&E>=1e3&&(this._params.onBandwidthChange({size:f,duration:E,speed:8*f/(E/1e3)}),f=0,l=g.length,h=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},o,(g,E,S)=>this._params.onError(g,E,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(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=gt._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(){this._mediaSource.readyState==="open"&&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),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class xi{_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=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(u,d)=>{const c=u?parseFloat(u.replace(",",".")):NaN;return(isNaN(c)?0:c)*d},i=t.exec(e),n=i?.[1]==="-"?-1:1,o={years:s(i?.[2],n),months:s(i?.[3],n),weeks:s(i?.[4],n),days:s(i?.[5],n),hours:s(i?.[6],n),minutes:s(i?.[7],n),seconds:s(i?.[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Ge(s)),new ms(s,t,i=>{this.attachManifest(i,t,Ii(s))},void 0,i=>{this._params.onResponseHeaders(i)},(i,n,o)=>this._params.onError(i,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(c,l)=>{const h=c.attributes.getNamedItem(l);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const u=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),c=>{const l=c.getElementsByTagName("SegmentBase")[0],h=l&&o(l,"indexRange").split("-"),f=l&&l.getElementsByTagName("Initialization")[0],m=f&&o(f,"range").split("-");if(!m||!h){const A=c.parentElement;if(A?.getAttribute("contentType")==="text"){const k=c.getAttribute("id")??void 0,y=(s?s+"/":"")+c.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,P=A.getAttribute("lang")??void 0;y&&d.push({id:k,url:y,language:P})}return}const p=.1,g=Number(c.attributes.getNamedItem("bandwidth")?.value),E=(s?s+"/":"")+c.getElementsByTagName("BaseURL")[0].childNodes[0].data;let S;const v=c.attributes.getNamedItem("frameRate")?.value??void 0;S=v?Rt(v):void 0,u.push({width:Number(c.attributes.getNamedItem("width")?.value),height:Number(c.attributes.getNamedItem("height")?.value),bandwidth:g,baseURL:E,failoverHosts:t,indexFrom:Number(h[0]),indexTo:Number(h[1]),initFrom:Number(m[0]),initTo:Number(m[1]),codecs:c.attributes.getNamedItem("codecs")?.value??void 0,mimeType:c.attributes.getNamedItem("mimeType")?.value??void 0,fps:S,bufferSize:p*g/8,bufferLength:p,name:c.attributes.getNamedItem("okQuality")?.value??void 0,id:c.attributes.getNamedItem("id")?.value??void 0})}),u.length)this._representations=u;else{this._onDashCallback("error");return}d.forEach(({id:c,language:l,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),c&&f.setAttribute("id",c),l&&f.setAttribute("srclang",l),this._video.appendChild(f)}),this._representations.sort((c,l)=>l.bandwidth-c.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,i=>{let n=e.initTo-e.initFrom+1;if(!i.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(i.buffer,0,n);const o=new DataView(i.buffer);n+=12;const u=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),c=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const l=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<l;f+=1){const m=c+(o.getUint32(n,!1)&2147483647),p=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/u,toTime:p/u,fromOffset:c,toOffset:m-1}),c=m,d=p}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,i=>{this._params.onResponseHeaders(i),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let i,n;const o=()=>{const c=this._findRef(this._video.currentTime);if(!c||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const m=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),m)}const l=this._appendVector[String(c.fromTime)];l!==i&&(i=l,this._params.onRepresentationPlay(l));let h;if(this._findRef(c.toTime)){const m=this._buffer.getByTime(this._video.currentTime);if(!m){this._onDashCallback("buffering");return}h=m.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==m.to&&(n=m.to,window.setTimeout(()=>{try{const p=this._buffer.getNextWithGap(m);p&&(this._video.currentTime=p.from)}catch(p){throw this._params.onError("GapSyncError",`Seek Error ${String(p)}`,p),p}},h*1e3)))}},u=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(c){throw this._params.onError("LoopError",`Dash Loop exception ${String(c)}`,c),c}u()},250)},d=()=>{if(!this._stream)try{const c=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new gt({mediaSource:s,sourceBuffer:c,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(c){throw this._params.onError("DashSourceOpen",`Source open exception ${String(c)}`,c),c}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||u(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const c=this._video&&this._video.played.length;c&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(c-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 n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),u=Math.abs(this._video.currentTime-t),d=i||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||u<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,u)=>this._stream.append(o,u),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(i.toTime<s.to+n){const o=this._findRef(i.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(i.fromTime-n,o.toTime+n,(u,d)=>this._stream.remove(u,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(i.fromTime-n,i.toTime+n,(u,d)=>this._stream.remove(u,d)),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 e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let i=0;i<t.length;i++){const n=t[i];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!s||n.fromTime<s.fromTime)&&(s=n)}if(!s){const i=t[t.length-1];if(e>i.toTime)return i}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(i*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var x;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(x||(x={}));const Bi=[x.PAUSED,x.PLAYING];class Vi{videoState=new G(x.STOPPED);subscription=new a.Subscription;video;buffer;dash;representations$=new a.ValueSubject([]);currentRepresentation$=new a.ValueSubject(void 0);params;textTracksManager=new me;elementSize$=new a.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=ke(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ni(this.video),this.dash=new xi({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:i,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:u})},i=()=>{const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:u},n=$e(this.video),o=(u,d)=>this.subscription.add(u.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.isAudioAvailable$,e.isAudioAvailable$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==N.Applying)&&(this.videoState.getState()===x.PLAYING||this.videoState.getState()===x.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Me(this.video,t.isLooped,s)),this.subscription.add(ve(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),o(bt(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===x.READY&&this.videoState.setState(x.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(x.PLAYING),T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(x.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(u=>{this.buffer.fill(),e.currentBuffer$.next(u)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:u,message:d,thrown:c})=>({id:`DashLite_${u}`,category:a.ErrorCategory.WTF,message:d,thrown:c}))).subscribe(this.params.output.error$)).add(a.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$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{const u=this.currentRepresentation$.getValue(),d=this.representations$.getValue(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.videoTrack.getState(),h=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),m=i();c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to);let p;if(!m&&a.isNonNullable(l))p=l;else{const g=Be(this.video.buffered,this.video.currentTime*1e3),E=m?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,S=Math.min(g/E,1);p=rt(d.map(({track:v})=>v),{container:f,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:S,playbackRate:this.video.playbackRate,current:d.find(({representation:v})=>v===u)?.track})?.id}return a.isNonNullable(p)?d.find(({track:g})=>g.id===p)?.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,s)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(u=>u.to===x.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(x.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((u,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&i()?u.height<=d.height:u===d)).subscribe(u=>{const d=Be(this.video.buffered,this.video.currentTime*1e3),c=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||c<=.5||!i())&&(this.dash.setQualityByRepresentation(u,!0),this.params.output.hostname$.next(ae(u.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(u=>{const{type:d,reused:c}=ps(u);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(c)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(u=>this.params.dependencies.throughputEstimator.addRawRtt(u))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const i=s.name??s.id??s.height.toString(10),n=(s.name&&nt(s.name))??Oe(s),o=s.bandwidth/1e3,u={width:s.width,height:s.height},d=s.fps;if(!n)continue;const c={id:i,quality:n,bitrate:o,size:u,fps:d};t.push({track:c,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map(({track:s})=>s)),this.videoState.setState(x.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:s})=>s===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return a.assertNonNullable(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(x.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(n)};`}),s===exports.PlaybackState.STOPPED){e!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("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(x.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(i?.to!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&Bi.includes(e)&&this.seek(n.position,n.forcePrecise),e){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_LOADED),this.prepare();return;case x.MANIFEST_LOADED:this.videoState.startTransitionTo(x.INITIAL_REPRESENTATION_SELECTED);return;case x.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(x.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case x.METADATA_LOADED:this.videoState.startTransitionTo(x.READY),this.dash.updateRefsForCurrentTime();return;case x.READY:s===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(x.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(x.PLAYING),this.playIfAllowed());return;case x.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(x.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case x.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(x.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(e)}}}var ue;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(ue||(ue={}));var yt;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(yt||(yt={}));var ce;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(ce||(ce={}));var O;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(O||(O={}));var ze;(function(r){r.MP4="mp4",r.WEBM="webm"})(ze||(ze={}));var wt=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const Oi=(r,e={})=>{const s=e.timeout||1,i=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-i-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Mi=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ut=Mi?Oi:window.requestIdleCallback;let Ss=!1;try{Ss=ls()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class Fi{bufferFull$=new a.Subject;error$=new a.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?!1: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?!1:new Promise(i=>{const n={operation:"remove",from:e,to:t,signal:s,callback:i};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let s;Ss&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:i}of this.queue)i(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}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",category:a.ErrorCategory.VIDEO_PIPELINE,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){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(i){i instanceof DOMException&&i.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):i instanceof DOMException&&i.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:i}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var Ht=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};const bs=new TextDecoder("ascii"),gs=r=>{let e=0,t=r.getUint32(e);e+=4;const s=new DataView(r.buffer,r.byteOffset+e,4),i=bs.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,r.byteLength)-e,o=new DataView(r.buffer,r.byteOffset+e,n);return{id:i,size:t,contents:o}},Ui=r=>bs.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Hi=(r,e,t)=>{const s=gs(r),i=[];let n=0;const o=()=>{const g=s.contents.getUint32(n);return n+=4,g};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const c=o(),l=o(),h=o(),f=o()&4294967295;let m=l/c*1e3,p=(t?t.to+1:r.byteOffset+r.byteLength)+h;for(let g=0;g<f;g++){const E=o(),S=E>>>31,v=E<<1>>>1,A=o();if(o(),S!==0)throw new Error("Unsupported multilevel sidx");const k=A/c*1e3;i.push({status:O.NONE,time:{from:m,to:m+k},byte:{from:p,to:p+v-1}}),m+=k,p+=v}return i},qi=r=>{let e=0,t=!1,s=!1;for(;e<=r.byteLength&&!t;){const i=new DataView(r.buffer,r.byteOffset+e);try{const n=gs(i);if(s||=n.id==="mdat",e+n.size<=r.byteLength)e+=n.size;else break}catch{t=!0}}return e>0&&e<=r.byteLength&&s?new DataView(r.buffer,r.byteOffset,e):null},Yi={validateData:Ui,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Hi,parseFeedableSegmentChunk:qi};var b;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(b||(b={}));var $;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})($||($={}));const qt={[b.EBML]:{type:$.Master},[b.EBMLVersion]:{type:$.UnsignedInteger},[b.EBMLReadVersion]:{type:$.UnsignedInteger},[b.EBMLMaxIDLength]:{type:$.UnsignedInteger},[b.EBMLMaxSizeLength]:{type:$.UnsignedInteger},[b.DocType]:{type:$.String},[b.DocTypeVersion]:{type:$.UnsignedInteger},[b.DocTypeReadVersion]:{type:$.UnsignedInteger},[b.Void]:{type:$.Binary},[b.Segment]:{type:$.Master},[b.SeekHead]:{type:$.Master},[b.Seek]:{type:$.Master},[b.SeekID]:{type:$.Binary},[b.SeekPosition]:{type:$.UnsignedInteger},[b.Info]:{type:$.Master},[b.TimestampScale]:{type:$.UnsignedInteger},[b.Duration]:{type:$.Float},[b.Tracks]:{type:$.Master},[b.Chapters]:{type:$.Master},[b.Cluster]:{type:$.Master},[b.Timestamp]:{type:$.UnsignedInteger},[b.SilentTracks]:{type:$.Master},[b.SilentTrackNumber]:{type:$.UnsignedInteger},[b.Position]:{type:$.UnsignedInteger},[b.PrevSize]:{type:$.UnsignedInteger},[b.SimpleBlock]:{type:$.Binary},[b.BlockGroup]:{type:$.Master},[b.EncryptedBlock]:{type:$.Binary},[b.Attachments]:{type:$.Master},[b.Tags]:{type:$.Master},[b.Cues]:{type:$.Master},[b.CuePoint]:{type:$.Master},[b.CueTime]:{type:$.UnsignedInteger},[b.CueTrackPositions]:{type:$.Master},[b.CueTrack]:{type:$.UnsignedInteger},[b.CueClusterPosition]:{type:$.UnsignedInteger},[b.CueRelativePosition]:{type:$.UnsignedInteger},[b.CueDuration]:{type:$.UnsignedInteger},[b.CueBlockNumber]:{type:$.UnsignedInteger},[b.CueCodecState]:{type:$.UnsignedInteger},[b.CueReference]:{type:$.Master},[b.CueRefTime]:{type:$.UnsignedInteger}},ys=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Et(r,t),i=s in qt,n=i?qt[s].type:$.Binary,o=r.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(r.buffer,r.byteOffset+t+1,u-1),c=o&255>>u,l=Et(d),h=c*2**((u-1)*8)+l,f=t+u;let m;return f+h>r.byteLength?m=new DataView(r.buffer,r.byteOffset+f):m=new DataView(r.buffer,r.byteOffset+f,h),{tag:i?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:m,valueSize:h}},Et=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Te=(r,e)=>{switch(e){case $.SignedInteger:return r.getInt8(0);case $.UnsignedInteger:return Et(r);case $.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case $.String:return new TextDecoder("ascii").decode(r);case $.UTF8:return new TextDecoder("utf-8").decode(r);case $.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case $.Master:return r;case $.Binary:return r;default:a.assertNever(e)}},ot=(r,e)=>{let t=0;for(;t<r.byteLength;){const s=new DataView(r.buffer,r.byteOffset+t),i=ys(s);if(!e(i))return;i.type===$.Master&&ot(i.value,e),t=i.value.byteOffset-r.byteOffset+i.valueSize}},ji=r=>{if(r.getUint32(0)!==b.EBML)return!1;let e,t,s;const i=ys(r);return ot(i.value,({tag:n,type:o,value:u})=>(n===b.EBMLReadVersion?e=Te(u,o):n===b.DocType?t=Te(u,o):n===b.DocTypeReadVersion&&(s=Te(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Es=[b.Info,b.SeekHead,b.Tracks,b.Chapters,b.Cluster,b.Cues,b.Attachments,b.Tags],Gi=[b.Timestamp,b.SilentTracks,b.SilentTrackNumber,b.Position,b.PrevSize,b.SimpleBlock,b.BlockGroup,b.EncryptedBlock],zi=r=>{let e,t,s,i,n=!1,o=!1,u=!1,d,c;return ot(r,({tag:l,type:h,value:f,valueSize:m})=>{if(l===b.SeekID){const p=Te(f,h);c=Et(p)}else l!==b.SeekPosition&&(c=void 0);return l===b.Segment?(e=f.byteOffset,t=f.byteOffset+m):l===b.Info?n=!0:l===b.SeekHead?o=!0:l===b.TimestampScale?s=Te(f,h):l===b.Duration?i=Te(f,h):l===b.SeekPosition&&c===b.Cues?d=Te(f,h):n&&o&&Es.includes(l)&&(u=!0),!u}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(i,"Failed to parse webm Segment duration"),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(i/1e9*s*1e3),cuesSeekPosition:d}},Qi=r=>{if(a.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wi=(r,e)=>{let t=!1,s=!1;const i=u=>a.isNonNullable(u.time)&&a.isNonNullable(u.position),n=[];let o;return ot(r,({tag:u,type:d,value:c})=>{switch(u){case b.Cues:t=!0;break;case b.CuePoint:o&&i(o)&&n.push(o),o={};break;case b.CueTime:o&&(o.time=Te(c,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:o&&(o.position=Te(c,d));break;default:t&&Es.includes(u)&&(s=!0)}return!(t&&s)}),o&&i(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:l}=u,h=n[d+1];return{status:O.NONE,time:{from:c,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},Ji=r=>{let e=0,t=!1;try{ot(r,s=>s.tag===b.Cluster?s.tagSize<=r.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Gi.includes(s.tag)?(e+s.tagSize<=r.byteLength&&(e+=s.tagSize,t||=[b.SimpleBlock,b.BlockGroup,b.EncryptedBlock].includes(s.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Ki={validateData:ji,parseInit:zi,getIndexRange:Qi,parseSegments:Wi,parseFeedableSegmentChunk:Ji};class Yt{onLastSegment$=new a.ValueSubject(!1);fullyBuffered$=new a.ValueSubject(!1);playingRepresentation$=new a.ValueSubject(void 0);error$=new a.Subject;gaps=[];subscription=new a.Subscription;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Ve;destroyAbortController=new Ve;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;constructor(e,t,s,i,{fetcher:n,tuning:o,getCurrentPosition:u,compatibilityMode:d=!1}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.container=s,s){case ze.MP4:this.containerParser=Yi;break;case ze.WEBM:this.containerParser=Ki;break;default:a.assertNever(s)}this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=a.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);a.assertNonNullable(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Fi(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,Ht(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const s=this.initData.get(t.id),i=this.segments.get(t.id);if(a.assertNonNullable(s,"No init buffer for starting representation"),a.assertNonNullable(i,"No segments for starting representation"),!(s instanceof ArrayBuffer))return;let n=0;for(const o of i)o.time.from-n>0&&this.gaps.push({representation:t.id,from:n,to:o.time.from}),n=o.time.to;a.isNonNullable(t.duration)&&t.duration-n>0&&this.gaps.push({representation:t.id,from:n,to:t.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=a.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);a.assertNonNullable(t,`No such representation ${e}`);let s=this.initData.get(e);if(a.isNullable(s)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const i=this.getCurrentPosition();a.isNonNullable(i)&&this.maintain(i)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ve,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const i=s.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Be(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&l>=i.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Ht(this.sourceBuffer.buffered)>=this.bufferLimit){const c=Be(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<l);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(s,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(u.includes(i))c="high";else{const l=u.at(0);l&&l.time.from-i.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status===O.FED&&!u.length&&Be(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=s.at(-1);d&&d.status===O.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(i===d))}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const s=this.segments.get(t);return s?s.find(n=>n.time.from<=e&&n.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(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){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex(({status:h,time:{from:f,to:m}},p)=>{const g=f<=s&&m>=s,E=f>s||g||p===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&f<=s+S||m<=s+S;return(h===O.NONE||h===O.PARTIALLY_EJECTED&&E&&v&&this.sourceBuffer&&!wt(this.sourceBuffer.buffered,s))&&E&&v});if(i===-1)return[];if(t!==ce.BYTE_RANGE)return e.slice(i,i+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let h=i;h<n.length&&(o<=c||u<=l);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===O.NONE||f.status===O.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,s="auto"){if(!e.length)return;let i,n,o=e;const{type:u}=t.segmentReference;switch(u){case ce.BYTE_RANGE:{i=t.segmentReference.url,n={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case ce.TEMPLATE:{const c=e.at(0);i=new URL(c.url,t.segmentReference.baseUrl).toString(),o=[c];break}default:a.assertNever(u)}for(const c of o)c.status=O.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await a.abortable(d,async function*(){const c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),d.aborted))for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);return void this.fetcher.fetch(i,{range:n,onProgress:(c,l)=>{if(!d.aborted)try{this.onSomeDataLoaded(c,t.id,n?n.from:0,l,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,c=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(c)})}onSegmentDownloadError(e){let t=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(t=Be(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,i,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},u=h=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=O.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of this.segments.get(f.id)??[])m.status===O.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=O.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const c=d.segmentReference.type,l=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,m=c===ce.BYTE_RANGE,p=m?f.byte.to-f.byte.from+1:l;if(h.representationId!==t||!(!m||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const E=m?f.byte.from-s:0,S=m?f.byte.to-s:e.byteLength,v=E<i,A=S<=i;if(f.status===O.DOWNLOADING&&v&&A){f.status=O.DOWNLOADED,this.activeSegments.delete(h);const k=new DataView(e.buffer,e.byteOffset+E,p);this.sourceBufferTaskQueue.append(k,n).then(y=>y&&!n.aborted?u(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(h.loadedBytes=Math.min(p,i-E),h.loadedBytes>h.feedingBytes)){const k=new DataView(e.buffer,e.byteOffset+E+h.feedingBytes,h.loadedBytes-h.feedingBytes),y=h.loadedBytes===p?k:this.containerParser.parseFeedableSegmentChunk(k);y?.byteLength&&(f.status=O.PARTIALLY_FED,h.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,n).then(P=>{if(n.aborted)o();else if(P)h.fedBytes+=y.byteLength,h.fedBytes===p&&u(h);else{if(h.feedingBytes<p)return;o()}}))}}}abortSegment(e){e.status===O.PARTIALLY_FED||e.status===O.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=O.NONE),e.status=O.PARTIALLY_EJECTED):e.status=O.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[i,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Ut(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const i=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,async function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,i)).then(u=>{if(!u)return;const{dataView:d,segments:c}=u,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let i=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const l="size"in c?c.size??0:c.byte.to-c.byte.from;i+=l};for(const c of this.segments.values())for(const l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status===O.FED&&d(l)}if(u=isFinite(n)&&isFinite(o),!u){i=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status===O.FED&&d(l)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const l=this.sourceBuffer.buffered.start(c)*1e3,h=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const m of f)if(m.status===O.NONE&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(h)){n=l,o=h;break}}if(u=isFinite(n)&&isFinite(o),!u&&s){i=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const h of l)h.time.from>e+c&&h.status===O.FED&&d(h)}return u=isFinite(n)&&isFinite(o),u?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")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 i={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&u>=s.time.to){i=void 0;break}u>s.time.from&&u<s.time.to&&(i.from=u),o<s.time.to&&o>s.time.from&&(i.to=o)}}i&&i.to-i.from>=1&&!this.gaps.some(n=>i&&n.from===i.from&&n.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ut(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const i=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:i,to:n})}const t=1;for(const s of this.segments.values())for(const i of s){const{status:n}=i;if(n!==O.FED&&n!==O.PARTIALLY_EJECTED)continue;const o=Math.floor(i.time.from),u=Math.ceil(i.time.to),d=e.some(l=>l.from-t<=o&&l.to+t>=u),c=e.filter(l=>o>=l.from-t&&o<=l.to+t||u>=l.from-t&&u<=l.to+t);d||(c.length===1?i.status=O.PARTIALLY_EJECTED:i.status=O.NONE)}}}var He;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(He||(He={}));class Xi{throughputEstimator;requestQuic;lastConnectionType$=new a.ValueSubject(void 0);lastConnectionReused$=new a.ValueSubject(void 0);lastRequestFirstBytes$=new a.ValueSubject(void 0);abortAllController=new Ve;subscription=new a.Subscription;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=ps(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=a.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ge(t));const s=yield je(t,{signal:this.abortAllController.signal}).catch(et);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=a.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?He.HEADER:He.PARAM,range:s,onProgress:i,priority:n="auto",signal:o,measureThroughput:u=!0}={}){let d=e;const c=new Headers;if(s)switch(t){case He.HEADER:{c.append("Range",`bytes=${s.from}-${s.to}`);break}case He.PARAM:{const I=new URL(d,location.href);I.searchParams.append("bytes",`${s.from}-${s.to}`),d=I.toString();break}default:a.assertNever(t)}this.requestQuic&&(d=Ge(d));let l=this.abortAllController.signal;if(o){const I=new Ve;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(o,"abort")).subscribe(()=>{try{I.abort()}catch(M){et(M)}})),this.abortAllController.signal.aborted||o.aborted)try{I.abort()}catch(M){et(M)}l=I.signal}const h=a.now(),f=yield je(d,{priority:n,headers:c,signal:l}).catch(et),m=a.now();if(this.throughputEstimator?.addRawRtt(m-h),!f)return null;if(!f.ok||!f.body)return Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const p=parseInt(f.headers.get("Content-Length")??"",10)||s&&s.to-s.from+1||NaN;if(!p){const I=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(I.byteLength,a.now()-m),i?.(new DataView(I),I.byteLength),I}if(!i&&!u)return f.arrayBuffer();const[g,E]=f.body.tee(),S=g.getReader();u&&this.throughputEstimator?.trackStream(E);let v=0;const A=new ArrayBuffer(p),k=new Uint8Array(A),y=new DataView(A);let P=!1;const C=I=>{P=!0,et(I)},U=a.abortable(l,async function*({done:I,value:M}){v===0&&this.lastRequestFirstBytes$.next(a.now()-h),!l.aborted&&(I?i?.(y,v):M&&(k.set(M,v),v+=M.byteLength,i?.(y,v),yield S?.read().then(U,C)))}.bind(this));return yield S?.read().then(U,C),P?null:A}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:i}=e;switch(i){case ce.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case ce.TEMPLATE:return await this.fetchTemplateRepresentation(e,s)??null;default:a.assertNever(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,async function*(e,t,s){if(e.type!==ce.BYTE_RANGE)return null;const{from:i,to:n}=e.initRange;let o=i,u=n,d=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,i),u=Math.max(l,n))),o=Math.min(o,0);const h=yield this.fetch(e.url,{range:{from:o,to:u},priority:s,measureThroughput:!1});if(!h)return null;const f=new DataView(h,i-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const m=t.parseInit(f),p=e.indexRange??t.getIndexRange(m);if(!p)throw new ReferenceError("No way to load representation index");let g;if(d)g=new DataView(h,p.from-o,p.to-p.from+1);else{const S=yield this.fetch(e.url,{range:p,priority:s,measureThroughput:!1});if(!S)return null;g=new DataView(S)}const E=t.parseSegments(g,m,p);return{dataView:new DataView(h),segments:E}}.bind(this));fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==ce.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});return i?{segments:e.segments.map(o=>({...o,status:O.NONE,size:void 0})),dataView:new DataView(i)}:null}.bind(this))}const et=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},jt=r=>{if(!r.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},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(r),i=s?.[1]==="-"?-1:1,n={days:e(s?.[5],i),hours:e(s?.[6],i),minutes:e(s?.[7],i),seconds:e(s?.[8],i)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},$t=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[i,n]of Object.entries(s)){const o=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>a.isNullable(n)?u:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Zi=(r,e)=>{const s=new DOMParser().parseFromString(r,"application/xml"),i={video:[],audio:[],text:[]},n=s.children[0],o=n.getElementsByTagName("Period")[0],u=o.children;let d;const c=n.getAttribute("mediaPresentationDuration"),l=o.getAttribute("duration");if(c)d=jt(c);else if(l){const p=jt(l);a.isNonNullable(p)&&(d=p)}let h=0;const f=n.getAttribute("profiles")?.split(",")??[],m=f.includes(yt.WEBM_AS_IN_FFMPEG)||f.includes(yt.WEBM_AS_IN_SPEC)?ze.WEBM:ze.MP4;for(const p of u){const g=p.getAttribute("mimeType"),E=p.getAttribute("codecs"),S=p.getAttribute("contentType")??g?.split("/")[0],v=p.getAttribute("profiles")?.split(",")??[],A=p.querySelectorAll("Representation"),k=p.querySelector("SegmentTemplate");if(S!=="text")for(const y of A){const P=y.getAttribute("mimeType")??g,C=y.getAttribute("codecs")??E??"",U=y.getAttribute("contentType")??P?.split("/")[0]??S,I=p.getAttribute("profiles")?.split(",")??[],M=parseInt(y.getAttribute("width")??"",10),j=parseInt(y.getAttribute("height")??"",10),B=parseInt(y.getAttribute("bandwidth")??"",10)/1e3,J=y.getAttribute("frameRate")??"",he=y.getAttribute("quality")??void 0,Pe=J?Rt(J):void 0,w=y.getAttribute("id")??(h++).toString(10),F=U==="video"?`${j}p`:U==="audio"?`${B}Kbps`:C,W=`${w}@${F}`,X=y.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(X,e).toString(),we=[...f,...v,...I];let Qe;const ut=y.querySelector("SegmentBase"),L=y.querySelector("SegmentTemplate")??k;if(ut){const Z=y.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[te,Se]=Z.split("-").map(Le=>parseInt(Le,10)),be={from:te,to:Se},de=y.querySelector("SegmentBase")?.getAttribute("indexRange"),[De,Ne]=de?de.split("-").map(Le=>parseInt(Le,10)):[],Re=de?{from:De,to:Ne}:void 0;Qe={type:ce.BYTE_RANGE,url:ie,initRange:be,indexRange:Re}}else if(L){const Z={representationId:y.getAttribute("id")??void 0,bandwidth:y.getAttribute("bandwidth")??void 0},te=parseInt(L.getAttribute("timescale")??"",10),Se=L.getAttribute("initialization")??"",be=L.getAttribute("media"),de=parseInt(L.getAttribute("startNumber")??"",10)??1,De=$t(Se,Z);if(!be)throw new ReferenceError("No media attribute in SegmentTemplate");const Ne=L.querySelectorAll("SegmentTimeline S")??[],Re=[];if(Ne.length){let Le=de,xe=0;for(const We of Ne){const Fe=parseInt(We.getAttribute("d")??"",10)*1e3,Je=parseInt(We.getAttribute("r")??"",10)||0,Ke=parseInt(We.getAttribute("t")??"",10)??void 0;for(let Ct=0;Ct<Je+1;Ct++){const As=$t(be,{...Z,segmentNumber:Le.toString(10),segmentTime:Ke.toString(10)}),Ps=Ke?Ke/te:xe;xe+=Fe/te;const ws=xe;Le++,Re.push({time:{from:Ps,to:ws},url:As})}}}else if(a.isNonNullable(d)){const xe=parseInt(L.getAttribute("duration")??"",10)/te*1e3,We=Math.ceil(d/xe);let Fe=0;for(let Je=1;Je<We;Je++){const Ke=$t(be,{...Z,segmentNumber:Je.toString(10),segmentTime:Fe.toString(10)});Re.push({time:{from:Fe,to:Fe+xe},url:Ke}),Fe+=xe}}Qe={type:ce.TEMPLATE,baseUrl:ie,initUrl:De,segments:Re}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!U||!P)continue;const ee={video:ue.VIDEO,audio:ue.AUDIO,text:ue.TEXT}[U];ee&&i[ee].push({id:W,kind:ee,segmentReference:Qe,profiles:we,duration:d,bitrate:B,mime:P,codecs:C,width:M,height:j,fps:Pe,quality:he})}}return{duration:d,container:m,representations:i}},ea=["timeupdate","progress","play","seeked","stalled","waiting"];var oe;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(oe||(oe={}));let ta=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new a.Subscription;fetcher;state$=new G(oe.NONE);currentVideoRepresentation$=new a.ValueSubject(void 0);error$=new a.Subject;lastConnectionType$=new a.ValueSubject(void 0);lastConnectionReused$=new a.ValueSubject(void 0);lastRequestFirstBytes$=new a.ValueSubject(void 0);forceEnded$=new a.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Ve;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Xi({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=a.abortable(this.destroyController.signal,async function*(e,t){this.element=e,this.state$.startTransitionTo(oe.MANIFEST_READY);const s=yield this.fetcher.fetchManifest(t).catch(o=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o}));if(!s)return;let i;try{i=Zi(s??"",t)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!i)return;const n=({mime:o,codecs:u})=>Boolean(e.canPlayType?.(o)&&window.MediaSource?.isTypeSupported?.(`${o}; codecs="${u}"`));this.manifest={...i,representations:Object.fromEntries(Object.entries(i.representations).map(([o,u])=>[o,u.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(oe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));initRepresentations=a.abortable(this.destroyController.signal,async function*(e,t){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(oe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Yt(ue.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(t)&&(this.audioBufferManager=new Yt(ue.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const i=a.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=a.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:i,someBufferEnded:n}).pipe(a.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(o=>!o.updating))try{this.source?.endOfStream()}catch(o){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.subscription.add(a.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(oe.REPRESENTATIOS_READY)}.bind(this));initBuffer(){a.assertNonNullable(this.element),this.state$.setState(oe.RUNNING),this.subscription.add(a.merge(...ea.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&wt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[ue.VIDEO]:this.videoBufferManager,[ue.AUDIO]:this.audioBufferManager,[ue.TEXT]:null}[e]?.switchTo(t)}seek(e,t){a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let s;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?s=e:s=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),wt(this.element.buffered,s)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(s),this.audioBufferManager?.maintain(s),this.element.currentTime=s/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(oe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const i of s.gaps)s.playingRepresentation$.getValue()===i.representation&&i.from<=e&&i.to>e&&(this.element.duration*1e3-i.to<this.tuning.endGapTolerance?t.push(1/0):t.push(i.to));if(t.length){const s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var z;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(z||(z={}));const sa=({id:r,width:e,height:t,bitrate:s,fps:i,quality:n})=>{const o=(n?nt(n):void 0)??Oe({width:e,height:t});return o&&{id:r,quality:o,bitrate:s,size:{width:e,height:t},fps:i}},ia=({id:r,bitrate:e})=>({id:r,bitrate:e}),aa=(r,e,t)=>{const s=e.indexOf(t);return r.at(Math.round(r.length*s/e.length))??r.at(-1)};class ra{subscription=new a.Subscription;videoState=new G(z.STOPPED);video;player;params;elementSize$=new a.ValueSubject(void 0);textTracksManager=new me;videoTracks=[];audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new pi;constructor(e){this.params=e,this.video=ke(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ta({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=$e(this.video),i=c=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:c})},n=(c,l)=>this.subscription.add(c.subscribe(l,i));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Me(this.video,t.isLooped,i)),this.subscription.add(ve(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,s.playbackRateState$,i)),n(bt(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===oe.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const l=this.player.getRepresentations();a.assertNonNullable(l,"Manifest not loaded or empty");const h=Array.from(l.audio).sort((p,g)=>g.bitrate-p.bitrate),f=Array.from(l.video).sort((p,g)=>g.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const g=ia(p);g&&this.audioTracks.push({track:g,representation:p})}for(const p of f){const g=sa(p);if(g){this.videoTracks.push({track:g,representation:p});const E=!this.params.tuning.isAudioDisabled&&aa(h,f,p);E&&this.audioRepresentations.set(p.id,E)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();a.assertNonNullable(m),this.player.initRepresentations(m.id,this.audioRepresentations.get(m.id)?.id)}else c===oe.REPRESENTATIOS_READY&&(this.videoState.setState(z.READY),this.player.initBuffer())},i));const o=c=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),l=this.player.state$.getTransition();if(c!==oe.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ue.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ue.AUDIO,f.id).catch(o)}},i)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(c=>c&&this.videoTracks.find(({representation:{id:l}})=>l===c)?.track)).subscribe(e.currentVideoTrack$,i)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(a.map(({to:c})=>c===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),s=this.videoTracks.find(({track:{id:h}})=>h===t)?.track,i=this.params.output.currentVideoTrack$.getValue(),n=Be(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(s&&!e?this.audioRepresentations.get(s.id)?.bitrate??0:0,i?this.audioRepresentations.get(i.id)?.bitrate??0:0),c=rt(this.videoTracks.map(({track:h})=>h),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:i,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),l=e?c??s:s??c;return l&&this.videoTracks.find(({track:h})=>h===l)?.representation}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state===N.Requested&&s?.to!==exports.PlaybackState.PAUSED&&e!==z.STOPPED&&t!==exports.PlaybackState.STOPPED&&this.seek(i.position,i.forcePrecise),t===exports.PlaybackState.STOPPED){e!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.player.stop(),this.video.removeAttribute("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(z.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();return;case z.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.READY&&T(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case z.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(e)}}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}const na=5e3,ge={};var V;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(V||(V={}));const ht=(r,e)=>new a.Observable(t=>{const s=(i,n)=>t.next(n);return r.on(e,s),()=>r.off(e,s)});class oa{subscription=new a.Subscription;videoState=new G(V.INITIALIZING);video;params;hls;textTracksManager=new me;trackLevels=new Map;constructor(e){this.video=ke(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}loadHlsJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),na);import("hls.js").then(i=>{e||(ge.Hls=i.default,ge.Events=i.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(ge.Hls,"hls.js not loaded"),this.hls=new ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(ge.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=c=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=$e(this.video),n=(c,l)=>this.subscription.add(c.subscribe(l,s));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.loadStart$,t.firstBytesEvent$),n(i.playing$,t.firstFrameEvent$),n(i.canplay$,t.canplay$),n(i.seeked$,t.seekedEvent$),n(i.isAudioAvailable$,t.isAudioAvailable$),n(i.inPiP$,t.inPiP$),n(i.inFullscreen$,t.inFullscreen$),this.subscription.add(Me(this.video,e.isLooped,s)),this.subscription.add(ve(this.video,e.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,i.playbackRateState$,s)),this.subscription.add(ht(this.hls,ge.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),T(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),T(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},s)),n(ht(this.hls,ge.Events.MANIFEST_PARSED).pipe(a.map(({levels:c})=>c.reduce((l,h)=>{const f=h.name||h.height.toString(10),{width:m,height:p}=h,g=nt(h.attrs.QUALITY??"")??Oe({width:m,height:p});if(!g)return l;const E=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,S={id:f.toString(),quality:g,bitrate:h.bitrate/1e3,size:{width:m,height:p},fps:E};return this.trackLevels.set(f,{track:S,level:h}),l.push(S),l},[]))),t.availableVideoTracks$),n(ht(this.hls,ge.Events.LEVEL_LOADING).pipe(a.map(({url:c})=>ae(c))),t.hostname$),this.subscription.add(pe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:s}));const o=c=>Array.from(this.trackLevels.values()).find(({level:l})=>l===c)?.track,u=ht(this.hls,ge.Events.LEVEL_SWITCHED).pipe(a.map(({level:c})=>o(this.hls.levels[c])));u.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,s),this.subscription.add(pe(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel])?.id,c=>{if(a.isNullable(c))return;const l=this.trackLevels.get(c)?.level;if(!l)return;const h=this.hls.levels.indexOf(l),f=this.hls.currentLevel,m=this.hls.levels[f];!m||l.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:u.pipe(a.map(c=>c?.id)),onError:s})),n(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!==V.INITIALIZING)switch(s?.to!==exports.PlaybackState.PAUSED&&i.state===N.Requested&&this.seek(i.position),t){case exports.PlaybackState.STOPPED:switch(e){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(e)}break;default:a.assertNever(t)}};prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(V.PLAYING),await Ie(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(V.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(V.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.removeAttribute("src"),this.video.load(),this.videoState.setState(V.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Gt="X-Playback-Duration";var zt=async r=>{const e=await je(r,{method:"HEAD"});return e.headers.has(Gt)?parseInt(e.headers.get(Gt),10):void 0};const ua=r=>{let e=null;if(r.QUALITY&&(e=nt(r.QUALITY)),!e&&r.RESOLUTION){const[t,s]=r.RESOLUTION.split("x").map(i=>parseInt(i,10));e=Oe({width:t,height:s})}return e??null},Ts=async(r,e=r)=>{const i=(await(await je(r)).text()).split(`
|
|
8
|
-
`),n=[];for(let o=0;o<i.length;o++){const d=i[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const c=Object.fromEntries(d[1].split(",").map(E=>E.split("="))),l=c.QUALITY??`stream-${c.BANDWIDTH}`,h=ua(c);let f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[E,S]=c.RESOLUTION.split("x").map(v=>parseInt(v,10));E&&S&&(p={width:E,height:S})}const g=new URL(i[++o],e).toString();h&&n.push({id:l,quality:h,url:g,bandwidth:f,size:p,fps:m})}return n};var H;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(H||(H={}));class ca{subscription=new a.Subscription;videoState=new G(H.STOPPED);video;params;textTracksManager=new me;manifests$=new a.ValueSubject([]);maxSeekBackTime$;liveOffset=new Nt;manifestStartTime$=new a.ValueSubject(void 0);constructor(e){this.params=e,this.video=ke(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]),Ts(Ye(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),n=i?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o)return;const u=s?"master":n;return s&&!i&&t.startTransitionTo("master"),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},i=$e(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,s));n(i.ended$,e.endedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.loadedMetadata$,e.firstBytesEvent$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.isAudioAvailable$,e.isAudioAvailable$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY),this.videoState.getState()===H.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(u=>-u/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&a.isNonNullable(c.to)){const h=c.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ae(f.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===H.CHANGING_MANIFEST&&this.videoState.setState(d.to),u&&u.state===N.Requested&&this.seek(u.position)},s)),this.subscription.add(i.loadedData$.subscribe(()=>{const u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},s)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:u,currentTime:d})=>this.params.output.liveTime$.next(u+d*1e3),s)),this.subscription.add(this.manifests$.pipe(a.map(u=>u.map(({id:d,quality:c,size:l,bandwidth:h,fps:f})=>({id:d,quality:c,size:l,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Ye(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),zt(t).then(s=>{if(!a.isNullable(s))this.maxSeekBackTime$.next(s);else{const i=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(a.isNullable(i)||!isFinite(i))try{je(t).then(n=>n.text()).then(n=>{const o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n)?.[1];if(o){const u=new URL(o,t).toString();zt(u).then(d=>{a.isNullable(d)||this.maxSeekBackTime$.next(d)})}})}catch{}}})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}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 e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===exports.PlaybackState.STOPPED){e!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.video.removeAttribute("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(H.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(e===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(i||n){const d=this.videoState.getState();this.videoState.setState(H.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),u.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==exports.PlaybackState.PAUSED&&u.state===N.Requested){this.videoState.startTransitionTo(H.READY),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case H.READY:t===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(H.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())):s?.to===exports.PlaybackState.PAUSED&&(T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case H.CHANGING_MANIFEST:break;default:return a.assertNever(e)}}}var Y;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(Y||(Y={}));class da{subscription=new a.Subscription;videoState=new G(Y.STOPPED);video;params;textTracksManager=new me;manifests$=new a.ValueSubject([]);constructor(e){this.params=e,this.video=ke(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.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),Ts(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),n=i?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o)return;const u=s?"master":n;return s&&!i&&t.startTransitionTo("master"),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},i=$e(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.loadedMetadata$,e.firstBytesEvent$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.seeked$,e.seekedEvent$),n(i.isAudioAvailable$,e.isAudioAvailable$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),this.subscription.add(Me(this.video,t.isLooped,s)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},s).add(i.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&a.isNonNullable(c.to)){const h=c.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ae(f.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===N.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe(a.map(u=>u.map(({id:d,quality:c,size:l,bandwidth:h,fps:f})=>({id:d,quality:c,size:l,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===exports.PlaybackState.STOPPED){e!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.removeAttribute("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(Y.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(e===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(i||n){const d=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:c}=this.video;this.prepare(),u.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:c*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&u.state===N.Requested&&this.seek(u.position),e){case Y.READY:t===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case Y.CHANGING_MANIFEST:break;default:return a.assertNever(e)}}}var Q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Q||(Q={}));class la{subscription=new a.Subscription;videoState=new G(Q.STOPPED);video;trackUrls={};params;textTracksManager=new me;constructor(e){this.params=e,this.video=ke(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],i)=>{const n=i.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},i=$e(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,s));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.loadedMetadata$,e.firstBytesEvent$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.seeked$,e.seekedEvent$),n(i.isAudioAvailable$,e.isAudioAvailable$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),this.subscription.add(Me(this.video,t.isLooped,s)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,s)),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&a.isNonNullable(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ae(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();a.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];a.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ge(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ae(t))}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.video.removeAttribute("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(Q.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(e===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:u*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&o.state===N.Requested&&this.seek(o.position),e){case Q.READY:t===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(e)}}}const Qt=["stun:videostun.mycdn.me:80"],ha=1e3,fa=3,At=()=>null;class pa{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=At;externalStopCallback=At;externalErrorCallback=At;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(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}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(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}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);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Qt}]};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(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,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(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}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{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),ha)}normalizeOptions(e={}){const t={stunServerList:Qt,maxRetryNumber:fa,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(q||(q={}));class ma{subscription;params;log;video;videoState=new G(q.STOPPED);liveStreamClient;maxSeekBackTime$=new a.ValueSubject(0);constructor(e){this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ke(e.container),this.liveStreamClient=new pa(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.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ae(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(o)}`})});const i=$e(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,s));n(i.timeUpdate$,e.liveTime$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(i.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.READY)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},s)).add(i.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},s)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},s)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==q.STOPPED&&(this.videoState.startTransitionTo(q.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(q.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case q.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(e)}}}class Wt{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)}}var Sa=()=>{const r=window.navigator;return r.userAgentData?r.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const vs=Sa(),Tt=document.createElement("video"),ye={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Tt.canPlayType?.("application/x-mpegurl")||Tt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},ne={mp4:Boolean(Tt.canPlayType?.("video/mp4")),webm:Boolean(Tt.canPlayType?.("video/webm")),cmaf:!0},_e={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"'))},Ue=(_e.h264||_e.h265)&&_e.aac,kt=ye.hls&&ne.mp4,ba=Boolean(window.WebSocket),ga=()=>Object.keys(_e).filter(r=>_e[r]),ya=(r,e=!1)=>r.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ye.mse&&ne.mp4&&Ue;case exports.VideoFormat.DASH_SEP:return ye.mse&&ne.mp4&&Ue;case exports.VideoFormat.DASH_WEBM:return ye.mse&&ne.webm&&_e.vp9&&_e.opus;case exports.VideoFormat.DASH_LIVE:return ye.mse&&ne.mp4&&Ue;case exports.VideoFormat.DASH_LIVE_CMAF:return ye.mse&&ne.mp4&&Ue&&ne.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return ye.mse&&ne.mp4&&Ue;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return kt||e&&ye.mse&&ne.mp4&&Ue;case exports.VideoFormat.MPEG:return ne.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ye.webrtc&&ba&&_e.h264&&(ne.mp4||ne.webm);default:return a.assertNever(t)}}),Ea=()=>vs?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:kt?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Ta=()=>vs?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:kt?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],Jt=r=>r?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var va=r=>new a.Observable(e=>{const t=new a.Subscription,s=r.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:c,to:l})=>`${c}-${l}`)),i=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$,o=new a.Subject;let u=0,d="unknown";return t.add(s.subscribe(c=>{u&&window.clearTimeout(u),d=c,u=window.setTimeout(()=>o.next(c),r.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(u),d="provider change",u=0})),t.add(n.subscribe(()=>{u&&(window.clearTimeout(u),u=window.setTimeout(()=>o.next(d),r.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});const Kt={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},ka={cacheDuration:12e4},$a={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Aa={maxPausedTime:3e4},Xt={maxPausedTime:3e4};class Pa{current$=new a.ValueSubject({type:void 0});providerError$=new a.Subject;noAvailableProvidersError$=new a.Subject;providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0)};subscription=new a.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=ya([...Ta(),...Ea()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:s}=this.params.tuning,i=s.length?[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:t;this.screenFormatsIterator=new Wt(i);const n=[...Jt(!0),...Jt(!1)];this.chromecastFormatsIterator=new Wt(n.filter(o=>a.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}s?this.current$.next({type:t,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.assertNonNullable(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),i=s.state!==N.None;this.params.desiredState.seekState.setState({state:N.Requested,position:i?s.position:t,forcePrecise:i?s.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case re.SCREEN:return this.createScreenProvider(t);case re.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:i}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),new Vi({...o,source:u,config:ka})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),this.params.tuning.useDashJs?new Ot({...o,source:u,format:e,config:Xt}):new ra({...o,source:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),new Ot({...o,source:u,format:e,config:Xt})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),kt||!this.params.tuning.useHlsJs?new da({...o,source:u}):new oa({...o,source:u})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),new ca({...o,source:u,config:Aa})}case exports.VideoFormat.MPEG:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),new la({...o,source:u})}case exports.VideoFormat.DASH_LIVE:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),new Ci({...o,source:u,config:$a})}case exports.VideoFormat.WEB_RTC_LIVE:{const u=this.applyFailoverHost(t[e]);return a.assertNonNullable(u),new ma({container:s,source:u,desiredState:i,output:n,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 a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:i,meta:n}=this.params,o=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(u),new Ws({connection:u,meta:n,container:s,source:t,format:e,desiredState:i,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?re.CHROMECAST:re.SCREEN}chooseFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case re.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.next();case re.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case re.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case re.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=i=>{const n=new URL(i);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return Object.fromEntries(Object.entries(e).map(([i,n])=>[i,s(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,s=0;return e.add(a.merge(this.providerOutput.error$,va({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Kt.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:i})=>i!==void 0))}).pipe(a.map(i=>({id:`ProviderHangup:${i}`,category:a.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const i=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{if(this.current$.getValue().destination===re.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=i.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=s<Kt.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Dt=(r,e,t)=>t*e+(1-t)*r,ks=(r,e)=>r.reduce((t,s)=>t+s,0)/e,wa=(r,e,t,s)=>{let i=0,n=t;const o=ks(r,e),u=e<s?e:s;for(let d=0;d<u;d++)r[n]>o?i++:i--,n=(r.length+n-1)%r.length;return Math.abs(i)===u};class $s{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new fe(`raw_${t}`),this.smoothedSeries$=new fe(`smoothed_${t}`),this.reportedSeries$=new fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const i=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*i,o=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.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))}}class Da extends $s{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Na extends $s{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ks(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);const s=wa(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Zt{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Da({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Na({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const Ra=5e3,es="one_video_throughput",ts="one_video_rtt",it=window.navigator.connection,ss=()=>{const r=it?.downlink;if(a.isNonNullable(r)&&r!==10)return r*1e3},is=()=>{const r=it?.rtt;if(a.isNonNullable(r)&&r!==3e3)return r},as=(r,e,t)=>{const s=t*8,i=s/r;return s/(i+e)};class at{throughput;rtt;subscription=new a.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=at.load(es)||(e.useBrowserEstimation?ss():void 0)||Ra,s=at.load(ts)??(e.useBrowserEstimation?is():void 0)??0;if(this.throughput$=new a.ValueSubject(t),this.rtt$=new a.ValueSubject(s),this.rttAdjustedThroughput$=new a.ValueSubject(as(t,s,e.rttPenaltyRequestSize)),this.throughput=Zt.getSmoothedValue(t,-1,e),this.rtt=Zt.getSmoothedValue(s,1,e),e.useBrowserEstimation){const i=()=>{const o=ss();o&&this.throughput.next(o);const u=is();a.isNonNullable(u)&&this.rtt.next(u)};it&&"onchange"in it&&this.subscription.add(a.fromEvent(it,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{a.safeStorage.set(es,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{a.safeStorage.set(ts,i.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:i,rtt:n})=>as(i,n,e.rttPenaltyRequestSize)),a.filter(i=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(i-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=a.now();const i=new a.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,s=a.now()}));break;case 1:case 0:i.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=a.now()}));break}i.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,u=a.now(),d=o-t,c=u-s;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let s=0;const i=a.now();let n=0,o=a.now();const u=c=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=async({done:c,value:l})=>{c?(this.addRawSpeed(s,a.now()-i,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),await t?.read().then(d,u))};this.concurrentDownloads.add(e),t?.read().then(d,u)}addRawSpeed(e,t,s=1){if(at.sanityCheck(e,t)){const i=e*8/t;this.throughput.next(i*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){const t=a.safeStorage.get(e);if(a.isNonNullable(t))return parseInt(t,10)??void 0}}const rs={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},_a=r=>{const e={};for(const t of Object.keys(rs)){const s=rs[t],i=r[t];Array.isArray(s)&&Array.isArray(i)?e[t]=i:typeof s=="object"&&typeof i=="object"?e[t]={...s,...i}:e[t]=i??s}return e};var Ca=({seekState:r,position$:e})=>a.merge(r.stateChangeEnded$.pipe(a.map(({to:t})=>t.state===N.None?void 0:(t.position??NaN)/1e3),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>r.getState().state===N.None))),Ia=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return a.assertNonNullable(e,`Wrong container or containerId {${r.container}}`),e};class La{subscription=new a.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new a.Logger;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new G(exports.PlaybackState.STOPPED),seekState:new G({state:N.None}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({})};info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)};events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject};experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:li};constructor(e={}){if(this.initLogs(),this.tuning=_a(e),this.chromecastInitializer=new Os({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new at(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,i)=>{const n=Reflect.get(t,s,i);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(u){const d=o.map(h=>JSON.stringify(h,(f,m)=>{const p=typeof m;return["number","string","boolean"].includes(p)?m:m===null?null:`<${p}>`})),c=`Player.${String(s)}`,l=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:a.ErrorCategory.WTF,message:l,thrown:u}),u}}}})}initVideo(e){return this.config=e,this.domContainer=Ia(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Pa({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}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:N.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(i=>i.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return(e===void 0||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(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===N.None?void 0:t.position;return a.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:i})=>s||i||0,0),height:e.reduce((s,{height:i})=>s||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===N.Requested?this.desiredState.seekState.setState({...o,state:N.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===N.Applying&&(this.desiredState.seekState.setState({state:N.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:u})=>u).sort((u,d)=>mt(u)?1:mt(d)?-1:ft(d,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const u={};for(const d of o)d.fps&&(u[d.quality]=d.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o?.quality),this.info.videoBitrate$.next(o?.bitrate)})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(a.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(a.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$}).pipe(a.map(({isLive:o,position:u})=>o&&u>-a.ACTIVE_LIVE_VALID_DELAY),a.filterChanged()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Ca({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o??a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>s.next(!1)));let i=0;const n=a.merge(e.providerOutput.isBuffering$,t,s).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||s.getValue();return o&&!u}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),c=this.chromecastInitializer.castState$.getValue();let l;c===exports.ChromecastState.CONNECTED?l=exports.Surface.SECOND_SCREEN:d?o?l=exports.Surface.PIP:u?l=exports.Surface.FULLSCREEN:l=exports.Surface.INLINE:l=exports.Surface.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((s,i)=>s.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(s=>s.length>0),a.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=rt(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(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.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 e=this.providerContainer?.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(e),di(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ci(t)),this.providerContainer.current$.subscribe(({type:t})=>ct("provider",t)),e.duration$.subscribe(t=>ct("duration",t)),e.availableVideoTracks$.pipe(a.filter(t=>!!t.length),a.once()).subscribe(t=>ct("tracks",t)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe(a.map(t=>t?.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(t=>this.subscription.add(t)),ct("codecs",ga())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(i)})})};this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const i=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!e?.released;i&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const xa=`${Bs}@${xs}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=La;exports.SDK_VERSION=xa;
|
|
6
|
+
"use strict";var Cs=Object.create;var Bt=Object.defineProperty;var Is=Object.getOwnPropertyDescriptor;var Ls=Object.getOwnPropertyNames;var xs=Object.getPrototypeOf,Bs=Object.prototype.hasOwnProperty;var Os=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ls(e))!Bs.call(r,a)&&a!==t&&Bt(r,a,{get:()=>e[a],enumerable:!(s=Is(e,a))||s.enumerable});return r};var Ot=(r,e,t)=>(t=r!=null?Cs(xs(r)):{},Os(e||!r||!r.__esModule?Bt(t,"default",{value:r,enumerable:!0}):t,r));var i=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),Ms=require("lodash/debounce.js");const Vs="2.0.86",Fs="esnext.cjs.js";exports.PlaybackState=void 0;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(r){r.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_CMAF="DASH_LIVE_CMAF",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.HLS_LIVE_CMAF="HLS_LIVE_CMAF",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var re;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(re||(re={}));exports.ChromecastState=void 0;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var P;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(P||(P={}));var Us=r=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",r),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Hs{connection$=new i.ValueSubject(void 0);castState$=new i.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new i.Subject;contentId;realCastState$=new i.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new i.Subscription;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const s=i.isNonNullable(window.chrome?.cast),a=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Us("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:i.ErrorCategory.NETWORK,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(){i.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();i.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();i.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(i.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=s.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 i.assertNever(a.sessionState)}})).add(i.merge(i.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(i.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),i.map(a=>a.castState)),i.observableFrom([s.getCastState()])).pipe(i.filterChanged(),i.map(qs),i.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{const n=a===exports.ChromecastState.CONNECTED,o=i.isNonNullable(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();i.assertNonNullable(u);const d=u.getCastDevice(),c=u.getMediaSession()?.media.contentId;(i.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?i.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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:i.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const qs=r=>{switch(r){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 i.assertNever(r)}};var Ge;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Ge||(Ge={}));var je=(r,e=0,t=Ge.OFFSET_P)=>{switch(t){case Ge.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Ge.PLAYBACK_SHIFT:{if(e===0)return r;const s=new URL(r);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:i.assertNever(t)}return r},T=(r,e,t=!1)=>{const s=r.getTransition();(t||!s||s.to===e)&&r.setState(e)};exports.VideoQuality=void 0;(function(r){r.INVARIANT="Invariant quality",r.Q_144P="144p",r.Q_240P="240p",r.Q_360P="360p",r.Q_480P="480p",r.Q_720P="720p",r.Q_1080P="1080p",r.Q_1440P="1440p",r.Q_2160P="2160p",r.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const he={[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}},mt=(r,e)=>he[r].height>he[e].height,Ys=(r,e)=>he[r].height>=he[e].height,it=(r,e)=>he[r].height<he[e].height,Gs=(r,e)=>he[r].height<=he[e].height,js=r=>r.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:it(e,t)?1:-1)[0],zs=Object.keys(he).sort((r,e)=>it(r,e)?-1:1),Fe=({width:r,height:e})=>{const t=Math.min(r,e),s=Math.max(r,e);return zs.find(a=>{const n=he[a];return n.width>=s&&n.height>=t})},Qs=r=>he[r].height,bt=r=>r===exports.VideoQuality.INVARIANT;class G{state;transition;transitionStarted$=new i.Subject;transitionEnded$=new i.Subject;transitionUpdated$=new i.Subject;forceChanged$=new i.Subject;stateChangeStarted$=i.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=i.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(e){const t=this.transition,s=this.state;s===e||i.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Ws=r=>{switch(r){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.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return i.assertNever(r)}};var w;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(w||(w={}));const Js=5,Ks=5,Xs=500,Mt=7e3;class Zs{subscription=new i.Subscription;loadMediaTimeoutSubscription=new i.Subscription;videoState=new G(w.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ws(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new i.Subscription;this.subscription.add(e),this.subscription.add(i.merge(this.videoState.stateChangeStarted$.pipe(i.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(i.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new i.Subject;e.add(a.pipe(i.debounce(Xs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(i.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const u=o.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state===P.Applying||Math.abs(u-n)>Js)&&a.next(u),n=u})),e.add(i.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(i.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(i.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(i.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.value,u=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(u!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Ks&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:i.assertNever(o)}}),t(i.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(i.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const s=i.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0));t(s,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),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(w.PLAYING),T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:P.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),T(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),T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===w.READY&&this.videoState.setState(w.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&T(this.params.desiredState.playbackState,exports.PlaybackState.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(e){const t=this.params.source;let s,a,n;switch(e){case exports.VideoFormat.MPEG:{const c=t[e];i.assertNonNullable(c);const l=js(Object.keys(c));i.assertNonNullable(l);const h=c[l];i.assertNonNullable(h),s=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=t[e];i.assertNonNullable(c),s=c.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=t[e];i.assertNonNullable(c),s=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=t[e];i.assertNonNullable(c),s=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=t[e];i.assertNonNullable(c),s=je(c.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:i.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:l}),l}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return i.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??s,a);o.contentUrl=s,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return i.isNonNullable(u)&&(o.metadata.title=u),i.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===P.Applying||s.state===P.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((a,n)=>{this.loadMediaTimeoutSubscription.add(i.timeout(Mt).subscribe(()=>n(`timeout(${Mt})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===P.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:i.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(n)};`}),s===exports.PlaybackState.STOPPED){e!==w.STOPPED&&(this.videoState.startTransitionTo(w.STOPPED),this.stop());return}if(!t){if(a?.to!==exports.PlaybackState.PAUSED&&n.state===P.Requested&&e!==w.STOPPED){this.seek(n.position/1e3);return}switch(s){case exports.PlaybackState.READY:{switch(e){case w.PLAYING:case w.PAUSED:case w.READY:break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:i.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case w.PLAYING:break;case w.PAUSED:this.videoState.startTransitionTo(w.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;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:i.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case w.PLAYING:this.videoState.startTransitionTo(w.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case w.PAUSED:break;case w.READY:this.videoState.startTransitionTo(w.PAUSED),this.videoState.setState(w.PAUSED);break;case w.STOPPED:this.videoState.startTransitionTo(w.READY),this.prepare();break;default:i.assertNever(e)}break}default:i.assertNever(s)}}}}class Vt{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 a=0,n=s.length;a<n;a++)if(s[a].callback===t){s.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let a=0,n=s.length;a<n;a++){const o=s[a];try{o.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class ds extends Vt{constructor(){super(),this.listeners||Vt.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let ls=class{constructor(){Object.defineProperty(this,"signal",{value:new ds,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(ls.prototype[Symbol.toStringTag]="AbortController",ds.prototype[Symbol.toStringTag]="AbortSignal");function hs(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function ei(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!hs({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(c,l){let h;l&&l.signal&&(h=l.signal,delete l.signal);const f=new t(c,l);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,c)=>{const l=n&&n.prototype.isPrototypeOf(d)?d.signal:c?c.signal:void 0;if(l){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(l.aborted)return Promise.reject(h);const f=new Promise((S,p)=>{l.addEventListener("abort",()=>p(h),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([f,o(d,c)])}return o(d,c)},Request:n}}const At=hs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),fs=At?ei({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ze=At?fs.fetch:window.fetch;At?fs.Request:window.Request;const Me=At?ls:window.AbortController,et=r=>r.range?r.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class at{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 a=t[0];if(!a||!a.request.range)continue;const[n,o]=et(a.request);if(n>=s.from&&o<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const a=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,a)}}}abort(e){if(e){const{request:t}=e,s=(this.dashJsRequestQueue.get(t.url)??[]).includes(e),a=this.activeRequests.get(t.url);s&&a&&a.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(et),a=s[0][0];let n=s[0][1];for(let f=1;f<s.length&&n<this.params.minDataSize;f++){const S=s[f][1];S-a<=2*this.params.minDataSize&&(n=Math.max(n,S))}a===0?n=Math.max(n,a+this.params.minInitSize):n=Math.max(n,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${a}-${n}`);const u=o.toString(),d=new Me,c=d.signal,l={url:e,from:a,to:n,loaded:0,data:null,abortController:d};c.addEventListener("abort",()=>this.onBigRequestAbort(l));const h=f=>{throw this.params.onError?.({id:"BigRequestParsing",category:i.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return ze(u,{signal:c}).then(f=>{if(l.response=f,!f.ok||!f.body){this.onBigRequestError(l);return}const[S,p]=f.body.tee();this.params.onDownloadStream?.(p);const m=S.getReader(),b=parseInt(f.headers.get("Content-Length")??"",10)||n-a+1;l.data=new ArrayBuffer(b);const v=new Uint8Array(l.data),$=async({done:F,value:E})=>{F?this.onBigRequestProgress(l):E&&(v.set(E,l.loaded),l.loaded+=E.byteLength,this.onBigRequestProgress(l),await m?.read().then($,at.suppressStreamErrors).catch(h))};m?.read().then($,at.suppressStreamErrors).catch(h)},at.suppressAbort).catch(f=>this.onBigRequestError(l,f)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:a,data:n,response:o}){if(!this.activeRequests.has(e)||!n)return;const u=this.dashJsRequestQueue.get(e)??[];for(const d of u){const{request:c}=d,[l,h]=et(c),f=l>=t&&h<=t+a,S=t>=l&&t+a<h,p=n.slice(l-t,Math.min(h-t+1,a));if((f||S)&&(c.requestStartDate=c.requestStartDate??new Date,c.firstByteDate=c.firstByteDate??new Date,c.bytesLoaded=p.byteLength,c.bytesTotal=s-t),f){c.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(b=>b!==d)),d.success?.(p,"",e);const m=o?Array.from(o.headers.entries()).map(([b,v])=>`${b}: ${v}`).join(`\r
|
|
7
|
+
`):"";this.dashMetrics?.addHttpRequest(c,e,o?.status??200,m,[])}else S&&d.progress?.({loaded:a,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},a){if(this.params.onError?.({id:"BigRequest",category:i.ErrorCategory.NETWORK,message:"Download error",thrown:a}),!this.activeRequests.has(e))return;const n=this.dashJsRequestQueue.get(e)??[];for(const o of n){const[u,d]=et(o.request);(u>=t&&u<s||d>t&&d<=s)&&o?.error?.(o.request,String(a))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:e,from:t,to:s}){if(!this.activeRequests.has(e))return;const a=this.dashJsRequestQueue.get(e)??[];for(const n of a){const[o,u]=et(n.request);(o>=t&&o<s||u>t&&u<=s)&&n?.abort?.(n.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class gt{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(gt.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;gt.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const ti=(r,e)=>t=>({create:s=>{const a=r(t).create(s);return new gt(a,e,s)}}),si=(r,e)=>{const t=new at(e);return r.extend("SchemeLoaderFactory",function(){const{parent:s}=this,a=s.getLoader;return{getLoader:n=>{const o=a(n);return ti(o,t)}}},!0),()=>t.destroy()};var ii=r=>{let e,t=!1,s=!1;r.on("playbackTimeUpdated",({timeToEnd:a})=>{s=a<=3,t&&s&&e?.()}),r.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&s&&e?.()}}},!0)},ai=r=>{const e=new i.ValueSubject(1/0),t=new i.Subject,s=new i.ValueSubject(void 0),a=new i.ValueSubject(void 0);let n=NaN,o=!1;const u=()=>{n=Date.now(),o=!1},d=l=>{const h=Object.fromEntries(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(p=>p.split(": ")));if("x-playback-duration"in h||"x-playback-duration-millis"in h){const p=parseInt(l.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(l.getResponseHeader("X-Playback-Duration-Millis")??"",10)??p*1e3??NaN;i.isNonNullable(b)&&!isNaN(b)&&e.next(b)}const f=h["x-delivery-type"]??exports.HttpConnectionType.HTTP1,S={1:!0,0:!1}[h["x-reused"]]??void 0;s.next(f),a.next(S)},c=l=>{l.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return r.extend("XHRLoader",function(){const{parent:l}=this,h=l.load.bind(l);return{load:function(f){if(f.request.type==="MPD"){const S=f.onload,p=f.progress;f.onload=function(...m){return d(this),S(...m)},f.progress=function(...m){return c(this),p(...m)},u()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:s}},Qe=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},ri=r=>r.extend("RequestModifier",()=>({modifyRequestURL:Qe}),!0),ni=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[a,n]=s.request.range.split("-").map(u=>parseInt(u,10)),o=new URL(s.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),s.request.url=o.toString(),s.request.range=void 0}t(s)}}},!0)};const me=(r,e,t,{equal:s=(o,u)=>o===u,changed$:a,onError:n}={})=>{const o=r.getState(),u=e(),d=i.isNullable(a),c=new i.Subscription;return a&&c.add(a.subscribe(l=>{const h=r.getState();s(l,h)&&r.setState(l)},n)),s(u,o)||(t(o),d&&r.setState(o)),c.add(r.stateChangeStarted$.subscribe(l=>{t(l.to),d&&r.setState(l.to)},n)),c},Ue=(r,e,t)=>me(e,()=>r.loop,s=>{i.isNonNullable(s)&&(r.loop=s)},{onError:t}),ke=(r,e,t,s)=>me(e,()=>({muted:r.muted,volume:r.volume}),a=>{i.isNonNullable(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,n)=>a===n||a?.muted===n?.muted&&a?.volume===n?.volume,changed$:t,onError:s}),Ie=(r,e,t,s)=>me(e,()=>r.playbackRate,a=>{i.isNonNullable(a)&&(r.playbackRate=a)},{changed$:t,onError:s}),oi=r=>["__",r.language,r.label].join("|"),ui=(r,e)=>{if(r.id===e)return!0;const[t,s,a]=e.split("|");return r.language===s&&r.label===a};class Se{available$=new i.Subject;current$=new i.ValueSubject(void 0);error$=new i.Subject;video;cueSettings;subscription=new i.Subscription;externalTracks=new Map;connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:i.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(me(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{i.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>i.isNonNullable(n)&&i.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(i.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(me(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(me(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){i.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(i.fromEvent(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(i.merge(i.fromEvent(e,"addtrack"),i.fromEvent(e,"removetrack"),i.observableFrom(["init"])).pipe(i.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),i.filterChanged((s,a)=>s.length===a.length&&s.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(i.merge(i.fromEvent(e,"change"),i.observableFrom(["init"])).pipe(i.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),i.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),i.filterChanged()).subscribe(this.current$));const t=s=>this.applyCueSettings(s.target?.activeCues??null);this.subscription.add(i.fromEvent(e,"addtrack").subscribe(s=>{s.track?.addEventListener("cuechange",t);const a=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",a))};s.track?.addEventListener("cuechange",a)})),this.subscription.add(i.fromEvent(e,"removetrack").subscribe(s=>{s.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const a=s;i.isNonNullable(t.align)&&(a.align=t.align),i.isNonNullable(t.position)&&(a.position=t.position),i.isNonNullable(t.size)&&(a.size=t.size),i.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){i.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Se.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,a=e.id!==""?e.id:oi(e);return this.externalTracks.has(a)?{id:a,type:"external",language:t,label:s,url:this.externalTracks.get(a).url}:{id:a,type:"internal",language:t,label:s}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){i.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))i.isNonNullable(e)&&ui(t,e)?t.mode="showing":t.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(e){i.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){i.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ae=r=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r.appendChild(e),e};class Ct{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(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}var ps=()=>{const{userAgent:r}=window.navigator;return!/chrome/i.test(r)&&/webkit|safari|khtml/i.test(r)};const Dt=3;class ci{_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 a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Dt&&(a=e),this._buffer.push({from:a,to:n,i:t})}return this._buffer.sort(function(t,s){return t.from-s.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||Dt))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:a,to:n})=>{const o=a>=e&&a<t,u=n>=e&&n<t;o&&u||(o?s(t,n):u?s(a,e):a<e&&n>t?(s(t,n),s(a,e)):s(a,n))})}destroy(){this._buffer=[]}}var ms=(r,e,t=Dt)=>{let s=0,a=0;for(let n=0;n<r.length;n++){const o=r.start(n),u=r.end(n);if(o<=e&&e<=u){if(s=o,a=u,!t)return{from:s,to:a};for(let d=n-1;d>=0;d--)r.end(d)+t>=s&&(s=r.start(d));for(let d=n+1;d<r.length;d++)r.start(d)-t<=a&&(a=r.end(d))}}return{from:s,to:a}};const di=50,li=r=>r.webkitAudioDecodedByteCount!==void 0?!!r.webkitAudioDecodedByteCount:r.mozHasAudio!==void 0?r.mozHasAudio:r.audioTracks?!!r.audioTracks.length:!0,$e=r=>{const e=p=>i.fromEvent(r,p).pipe(i.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=i.merge(...t.map(p=>i.fromEvent(r,p))).pipe(i.map(p=>p.type==="ended"?r.readyState<2:r.readyState<3),i.filterChanged()),a=i.merge(i.fromEvent(r,"progress"),i.fromEvent(r,"timeupdate")).pipe(i.map(()=>ms(r.buffered,r.currentTime))),n=ps()?i.combine({play:e("play").pipe(i.once()),playing:e("playing")}).pipe(i.mapTo(void 0)):e("playing"),o=i.fromEvent(r,"playing").pipe(i.debounce(di),i.map(()=>li(r))),u=i.fromEvent(r,"volumechange").pipe(i.map(()=>({muted:r.muted,volume:r.volume}))),d=i.fromEvent(r,"ratechange").pipe(i.map(()=>r.playbackRate)),c=i.fromEvent(r,"error").pipe(i.filter(()=>Boolean(r.error||r.played.length)),i.map(()=>{const p=r.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:i.ErrorCategory.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=i.fromEvent(r,"timeupdate").pipe(i.map(()=>r.currentTime)),h=new i.Subject,f=.3;let S;return l.subscribe(p=>{r.loop&&i.isNonNullable(S)&&i.isNonNullable(p)&&S>=r.duration-f&&p<=f&&h.next(S),S=p}),{playing$:n,pause$:e("pause").pipe(i.filter(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:i.fromEvent(r,"durationchange").pipe(i.map(()=>r.duration)),isBuffering$:s,currentBuffer$:a,volumeState$:u,isAudioAvailable$:o,playbackRateState$:d}},It=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let Lt=!1,Te={};const hi=r=>{Lt=r},fi=()=>{Te={}},pi=r=>{r(Te)},lt=(r,e)=>{Lt&&(Te.meta=Te.meta??{},Te.meta[r]=e)};class pe{name;constructor(e){this.name=e}next(e){if(!Lt)return;Te.series=Te.series??{};const t=Te.series[this.name]??[];t.push([Date.now(),e]),Te.series[this.name]=t}}const mi=new pe("best_bitrate"),Si=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class bi{last;history={};recordSelection(e){this.history[e.id]=i.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ot=(r,{container:e,throughput:t,tuning:s,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:c})=>{const l=s.usePixelRatio?window.devicePixelRatio??1:1,h=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*s.containerSizeFactor,height:e.height*l*s.containerSizeFactor},f=h&&Fe(h),S=s.considerPlaybackRate&&i.isNonNullable(u)?u:1,p=r.filter(_=>!bt(_.quality)).sort((_,q)=>mt(_.quality,q.quality)?-1:1),m=p.at(-1)?.quality,b=p.at(0)?.quality,v=i.isNullable(a)||i.isNonNullable(a.min)&&i.isNonNullable(a.max)&&it(a.max,a.min)||i.isNonNullable(a.min)&&b&&mt(a.min,b)||i.isNonNullable(a.max)&&m&&it(a.max,m),$=S*Si(o??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),E=p.filter(_=>{const q=f?it(_.quality,f):!0,C=i.isNonNullable(t)&&isFinite(t)&&i.isNonNullable(_.bitrate)?t-n>=_.bitrate*$:!0,M=s.lazyQualitySwitch&&i.isNonNullable(s.minBufferToSwitchUp)&&d&&!bt(d.quality)&&(o??0)<s.minBufferToSwitchUp&&mt(_.quality,d.quality),j=v||(i.isNullable(a.max)||Gs(_.quality,a.max))&&(i.isNullable(a.min)||Ys(_.quality,a.min));return q&&C&&!M&&j})[0];E&&E.bitrate&&mi.next(E.bitrate);const y=E??p[Math.ceil((p.length-1)/2)]??r[0],R=y&&c&&c.history[y.id]&&i.now()-c.history[y.id]<=s.trackCooldown&&(!c.last||y.id!==c.last.id);if(y?.id&&c&&!R&&c.recordSelection(y),R&&c?.last){const _=c.last;return c?.recordSwitch(_),_}return c?.recordSwitch(y),y};var ae=r=>new URL(r).hostname;const gi=300,yt=(r,e=gi)=>new i.Observable(t=>{const{width:s,height:a}=r.getBoundingClientRect();if(t.next({width:s,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(Ms(o=>{const u=o[0];if(!u)return;let d,c;u.contentBoxSize&&u.contentBoxSize[0]?(c=u.contentBoxSize[0].blockSize,d=u.contentBoxSize[0].inlineSize):u.contentRect&&(d=u.contentRect.width,c=u.contentRect.height),i.isNonNullable(d)&&i.isNonNullable(c)&&t.next({width:d,height:c})},e));return n.observe(r),()=>n.disconnect()}),Pe=r=>{try{r.pause(),r.playbackRate=0,r.removeAttribute("src"),r.load(),r.remove()}catch(e){console.error(e)}},yi=5e3,tt={};var D;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(D||(D={}));const K=(r,e)=>new i.Observable(t=>{const s=a=>t.next(a);return r.on(e,s),()=>r.off(e,s)});class Ft{subscription=new i.Subscription;videoState=new G(D.DOWNLOADING_LIB);video;player;params;textTracksManager=new Se;videoTracks=[];frameRatesByFrameHeight={};isLive$=new i.ValueSubject(void 0);maxSeekBackTime$=new i.ValueSubject(1/0);availableFrom$=new i.ValueSubject(void 0);elementSize$=new i.ValueSubject(void 0);liveOffset=new Ct;destroyBigRequest;constructor(e){this.video=Ae(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:i.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${a?.toString?.()}`,thrown:a}),e=!0},s=window.setTimeout(()=>t("timeout"),yi);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(tt.MediaPlayer=a.MediaPlayer,tt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){i.assertNonNullable(tt.MediaPlayer,"dashjs not loaded"),i.assertNonNullable(tt.Debug,"dashjs not loaded"),this.player=tt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?It(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=si(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&ni(this.player),ii(this.player),this.params.tuning.requestQuick&&ri(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(D.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=m=>{e.error$.next({id:"DashIFProvider",category:i.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},a=(m,b)=>this.subscription.add(m.subscribe(b,s));a(yt(this.video),this.elementSize$),a(K(this.player,"error").pipe(i.map(m=>{const b=typeof m.error=="object"?m.error.code:m.error,v=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${b}`,message:v}})),e.error$),a(K(this.player,"playbackError").pipe(i.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=K(this.player,"qualityChangeRendered").pipe(i.filter(({mediaType:m})=>m==="video"),i.map(({newQuality:m})=>this.videoTracks.find(({bitrateInfo:b})=>b.qualityIndex===m)?.track));n.pipe(i.filter(i.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(i.filter(({to:m})=>m===D.STREAM_INITIALIZED),i.once()).subscribe(()=>{this.subscription.add(me(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:b})=>b.qualityIndex===m)?.track?.id},m=>{if(i.isNullable(m))return;const b=this.videoTracks.find(({track:v})=>v.id===m)?.bitrateInfo;b&&this.player.setQualityFor("video",b.qualityIndex)},{changed$:n.pipe(i.map(m=>m?.id)),onError:s}))},s)),this.subscription.add(me(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:s})),a(K(this.player,"bufferStateChanged").pipe(i.filter(({mediaType:m})=>m==="video"),i.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),a(K(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:b}})=>{const v=this.player.getDashMetrics(),$=v.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),F=v.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??exports.HttpConnectionType.HTTP1,E={1:!0,0:!1}[$]??void 0;this.params.output.httpConnectionType$.next(F),this.params.output.httpConnectionReused$.next(E),e.hostname$.next(ae(b))}),a(K(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:b,availableFrom:v}}})=>{this.isLive$.next(b),this.availableFrom$.next(v.getTime()),b||e.duration$.next(m),this.videoTracks=[];const $=this.player.getQualityFor("video");let F;for(const E of this.player.getBitrateInfoListFor("video")){const y=E.qualityIndex.toString(10),R=Fe(E),_=E.bitrate/1e3,q={width:E.width,height:E.height},C=this.frameRatesByFrameHeight[E.height];if(R){const M={id:y,quality:R,bitrate:_,size:q,fps:C};this.videoTracks.push({track:M,bitrateInfo:E}),E.qualityIndex===$&&(F=M)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),F&&e.currentVideoTrack$.next(F),this.videoState.setState(D.STREAM_INITIALIZED),this.videoState.startTransitionTo(D.READY)}),a(K(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const b=m.requestEndDate.getTime()-m.firstByteDate.getTime(),v=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(v,b)}),a(i.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=ot(this.videoTracks.map(({track:$})=>$),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),v=this.videoTracks.find(({track:$})=>$===b);v?.bitrateInfo&&this.player.setQualityFor("video",v?.bitrateInfo.qualityIndex,!1)}),a(i.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(i.filter(i.isNonNullable))}).pipe(i.filter(({isLive:m})=>m),i.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=K(this.player,"playbackTimeUpdated").pipe(i.map(({time:m})=>m??0));a(i.combine({availableFrom:this.availableFrom$.pipe(i.filter(i.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:b})=>this.params.output.liveTime$.next(m+b*1e3)),a(o.pipe(i.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(K(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(K(this.player,"playbackEnded"),e.endedEvent$),a(K(this.player,"playbackProgress").pipe(i.map(()=>ms(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(K(this.player,"playbackPlaying"),()=>{this.videoState.setState(D.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)}),a(K(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(D.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(K(this.player,"playbackPaused"),()=>{this.videoState.setState(D.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)}),a(K(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===D.READY&&this.videoState.setState(D.READY)}),a(this.isLive$,e.isLive$),a(yt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const u=i.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0));a(u,this.syncPlayback);const{playbackDuration$:d,ping$:c,connectionType$:l,connectionReused$:h}=ai(this.player);a(l,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(c.pipe(i.once()),e.firstBytesEvent$),a(K(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(i.combine({isLive:this.isLive$,isShort:e.duration$.pipe(i.map(m=>m<60))}),({isLive:m,isShort:b})=>{const v=!m&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:v}}})}),a(o.pipe(i.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),i.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(K(this.player,"manifestLoaded").pipe(i.once()).subscribe(()=>{this.subscription.add(K(this.player,"playbackPlaying").pipe(i.once(),i.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(Ue(this.video,t.isLooped,s));const{volumeState$:f,looped$:S,playbackRateState$:p}=$e(this.video);this.subscription.add(ke(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(S.subscribe(e.loopedEvent$)),this.subscription.add(Ie(this.video,t.playbackRate,p,s))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(D.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(D.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 a=je(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ge.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(D.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(D.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===D.DOWNLOADING_LIB||e===D.STREAM_INITIALIZED))switch(s?.to!==exports.PlaybackState.PAUSED&&a.state===P.Requested&&e!==D.STOPPED&&t!==exports.PlaybackState.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),t){case exports.PlaybackState.STOPPED:{switch(e){case D.STOPPED:break;case D.PLAYING:case D.PAUSED:case D.READY:this.stop();break;default:i.assertNever(e)}break}case exports.PlaybackState.READY:{switch(e){case D.STOPPED:this.prepare();break;case D.PLAYING:case D.PAUSED:case D.READY:break;default:i.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case D.PLAYING:break;case D.PAUSED:n&&(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 D.READY:this.play();break;case D.STOPPED:this.prepare();break;default:i.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case D.PLAYING:this.pause(),this.liveOffset.pause();break;case D.PAUSED:break;case D.READY:this.videoState.setState(D.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case D.STOPPED:this.prepare();break;default:i.assertNever(e)}break}default:i.assertNever(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch{}Pe(this.video),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var ut=r=>{switch(r){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}};const Ut=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Le=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!Ut(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(s){return Ut(s)&&(r.muted=!1,console.warn(s)),!1}}return!0};function se(){return i.now()}function Ss(r){return se()-r}function Ht(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,a=o=>s.test(o);return{resolve:(o,u,d=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let c=o.indexOf("?")>-1?"&":"?";return d&&(o+=c+"lowLat=1",c="&"),u&&(o+=c+"_rnd="+Math.floor(999999999*Math.random())),o}}}function Ei(r,e,t){const s=(...a)=>{t.apply(null,a),r.removeEventListener(e,s)};r.addEventListener(e,s)}function St(r,e,t,s){const a=window.XMLHttpRequest;let n,o,u,d=!1,c=0,l,h,f=!1,S="arraybuffer",p=7e3,m=2e3,b=()=>{if(d)return;i.assertNonNullable(l);const O=Ss(l);let J;if(O<m){J=m-O,setTimeout(b,J);return}m*=2,m>p&&(m=p),o&&o.abort(),o=new a,R()};const v=O=>(n=O,j),$=O=>(h=O,j),F=()=>(S="json",j),E=()=>{if(!d){if(--c>=0){b(),s&&s();return}d=!0,h&&h(),t&&t()}},y=O=>(f=O,j),R=()=>{l=se(),o=new a,o.open("get",r);let O=0,J,fe=0;const we=()=>(i.assertNonNullable(l),Math.max(l,Math.max(J||0,fe||0)));if(n&&o.addEventListener("progress",A=>{const V=se();n.updateChunk&&A.loaded>O&&(n.updateChunk(we(),A.loaded-O),O=A.loaded,J=V)}),u&&(o.timeout=u,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;i.assertNonNullable(o);const A=o.status;if(A>=200&&A<300){if(o.response.byteLength&&n){const V=o.response.byteLength-O;V&&n.updateChunk&&n.updateChunk(we(),V)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const A=()=>{i.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(fe=se(),o.removeEventListener("readystatechange",A))};o.addEventListener("readystatechange",A)}return o.responseType=S,o.send(),j},j={withBitrateReporting:v,withParallel:y,withJSONResponse:F,withRetryCount:O=>(c=O,j),withRetryInterval:(O,J)=>(i.isNonNullable(O)&&(m=O),i.isNonNullable(J)&&(p=J),j),withTimeout:O=>(u=O,j),withFinally:$,send:R,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return j}const Ti=100,vi=2e3,ki=500;let Ai=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),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):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-ki;if(t-e>vi){let s=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,u=n.end-n.start;s+=o;const d=n.bytes*o/u;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&s>0){const n=a*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${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>Ti&&(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 $i{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,a,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=a,this.logger=n}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(),a=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=se()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=St(t,n,()=>a("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),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):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_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,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=a,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=a,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}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}}const ht=1e4,ft=3,Pi=300,wi=2e3,Ni=6e4,Di=10,Ri=1,_i=500;class Ci{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 Ai(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ht(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){this._switchToQuality(t);return}}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=Ht(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 s!==0&&(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",()=>{Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):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 a;s!==0&&(a=t.buffered.start(s-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let s,a,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u)n=this.manifest[u],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!a||n.bitrate>a.bitrate)&&(a=n):(!s||s.bitrate>n.bitrate)&&(s=n));return a||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||i.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{Ei(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new $i(ft,ht,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:a}=this.params;let n=!1,o=null,u=null,d=null,c=null,l=!1;const h=()=>{const E=n&&(!l||l===this.rep);return E||t("Not running!"),E},f=(E,y,R)=>{d&&d.abort(),d=St(this.urlResolver.resolve(E,!1),y,R,()=>this._retryCallback()).withTimeout(ht).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ft).withFinally(()=>{d=null}).send()},S=(E,y,R)=>{i.assertNonNullable(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),y,R,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},p=E=>{const y=s.playbackRate;s.playbackRate!==E&&(t(`Playback rate switch: ${y}=>${E}`),s.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}const R=se()-1e4;let _=0;for(let C=0;C<this.bufferStates.length;C++){const M=this.bufferStates[C];E=Math.min(E,M.buf),M.ts<R&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${E} drop=${_} jitter=${this.sourceJitter}`);let q=E-Ri;this.sourceJitter>=0?q-=this.sourceJitter/2:this.sourceJitter-=1,q>3?p(1.15):q>1?p(1.1):q>.3?p(1.05):p(1)}},v=E=>{let y;const R=()=>y&&y.start?y.start.length:0,_=A=>y.start[A]/1e3,q=A=>y.dur[A]/1e3,C=A=>y.fragIndex+A,M=(A,V)=>({chunkIdx:C(A),startTS:_(A),dur:q(A),discontinuity:V}),j=()=>{let A=0;if(y&&y.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=V;this.sourceJitter>1&&(X+=this.sourceJitter-1);let ie=y.dur.length-1;for(;ie>=0&&(X-=y.dur[ie],!(X<=0));--ie);A=Math.min(ie,y.dur.length-1-W),A=Math.max(A,0)}return M(A,!0)},O=A=>{const V=R();if(!(V<=0)){if(i.isNonNullable(A)){for(let W=0;W<V;W++)if(_(W)>A)return M(W)}return j()}},J=A=>{const V=R(),W=A?A.chunkIdx+1:0,X=W-y.fragIndex;if(!(V<=0)){if(!A||X<0||X-V>Di)return t(`Resync: offset=${X} bChunks=${V} chunk=`+JSON.stringify(A)),j();if(!(X>=V))return M(W-y.fragIndex,!1)}},fe=(A,V,W)=>{c&&c.abort(),c=St(this.urlResolver.resolve(A,!0,this.lowLatency),V,W,()=>this._retryCallback()).withTimeout(ht).withRetryCount(ft).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(A,V)=>{fe(E,W=>{if(!h())return;y=W;const X=Boolean(y.lowLatency);X!==this.lowLatency&&m(X);let ie=0;for(let Ne=0;Ne<y.dur.length;++Ne)ie+=y.dur[Ne];ie>0&&(i.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,A(O(V))},()=>this._handleNetworkError())},nextChunk:J}},$=()=>{n=!1,u&&u.abort(),d&&d.abort(),c&&c.abort(),i.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:y,logger:R}=this.params;let _=v(e.jidxUrl),q,C,M,j,O=0,J,fe,we;const A=()=>{J&&(clearTimeout(J),J=void 0);const I=Math.max(_i,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ee=O+I,Z=se(),te=Math.min(1e4,ee-Z);O=Z;const be=()=>{c||h()&&_.seek(()=>{h()&&(O=se(),V(),A())})};te>0?J=window.setTimeout(()=>{this.paused?A():be()},te):be()},V=()=>{let I;for(;I=_.nextChunk(j);)j=I,Je(I);const ee=_.nextChunk(M);if(ee){if(M&&ee.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?A():($(),this._initPlayerWith(e));return}Ne(ee)}else A()},W=(I,ee)=>{if(!h()||!this.sourceBuffer)return;let Z,te,be;const ge=le=>{window.setTimeout(()=>{h()&&W(I,ee)},le)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),ge(100);else{const le=se(),De=y.currentTime;!this.paused&&y.buffered.length>1&&fe===De&&le-we>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),fe!==De&&(fe=De,we=le);const Re=this._getBufferSizeSec();if(Re>30)R(`Buffered ${Re} seconds; delaying appendBuffer`),ge(2e3);else try{this.sourceBuffer.appendBuffer(I),this.videoPlayStarted?(this.bufferStates.push({ts:le,buf:Re}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ee&&ee()}catch(_e){if(_e.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),be=this.sourceBuffer.buffered.length,be!==0&&(Z=this.sourceBuffer.buffered.start(0),te=De,te-Z>4&&this.sourceBuffer.remove(Z,te-3)),ge(1e3);else throw _e}}},X=()=>{C&&q&&(R([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(M)]),W(C,function(){C=null,V()}))},ie=I=>e.fragUrlTemplate.replace("%%id%%",I.chunkIdx),Ne=I=>{h()&&S(ie(I),(ee,Z)=>{if(h()){if(Z/=1e3,C=ee,M=I,o=I.startTS,Z){const te=Math.min(10,I.dur/Z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*te:te}X()}},()=>this._handleNetworkError())},Je=I=>{h()&&(i.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(I),!1)))},dt=I=>{h()&&(e.cachedHeader=I,W(I,()=>{q=!0,X()}))};n=!0,_.seek(I=>{if(h()){if(O=se(),!I){A();return}j=I,!i.isNullable(E)||I.startTS>E?Ne(I):(M=I,V())}},E),e.cachedHeader?dt(e.cachedHeader):f(e.headerUrl,dt,()=>this._handleNetworkError())},stop:$,getTimestampSec:()=>o},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),i.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,i.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return i.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,S,p;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(S=this._getBufferSizeSec(),p=h/this.bitrate,S>10&&p>.8||S>15&&p>.5||S>20&&p>.3)){e(`Not switching: buffer=${Math.floor(S)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,S)=>{const p=se();if(this.chunkRateEstimator.addInterval(f,p,S)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:S,duration:p-f,speed:b}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,u,d=!0;const c=()=>{let h=n.get();if(h&&u&&this.autoQuality){if(d&&h>u&&Ss(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const S=n.updateChunk(h,f);return S&&c(),S},notifySwitch:h=>{const f=se();h<u&&(o=f),u=h}}}_fetchManifest(e,t,s){this.manifestRequest=St(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ht).withRetryCount(ft).withRetryInterval(Pi,wi).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Le(t).then(s=>{s||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:a}=this.params,n=o=>{const u=[];return o?.length?(o.forEach((d,c)=>{d.video&&a.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=c,u.push(d))}),u.sort(function(d,c){return d.video&&c.video?c.video.height-d.video.height:c.bitrate-d.bitrate}),u):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(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))},Ni))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var N;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(N||(N={}));const Ii=[N.PAUSED,N.PLAYING,N.READY],Li=[N.PAUSED,N.PLAYING,N.READY];class xi{subscription=new i.Subscription;video;videoState=new G(N.STOPPED);dash;representations$=new i.ValueSubject([]);textTracksManager=new Se;maxSeekBackTime$=new i.ValueSubject(1/0);zeroTime$=new i.ValueSubject(void 0);liveOffset=new Ct;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:i.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};i.merge(this.videoState.stateChangeStarted$.pipe(i.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(i.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=Ae(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=$e(this.video);this.subscription.add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===N.READY&&this.videoState.setState(N.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(N.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===P.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(N.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(i.filterChanged(),i.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(i.combine({zeroTime:this.zeroTime$.pipe(i.filter(i.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(Ue(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Ie(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&Qs(a);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case N.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case N.MANIFEST_READY:case N.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case N.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case N.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return i.assertNever(a.to)}},t)).add(i.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}createLiveDashPlayer(){const e=new Ci({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,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!s&&i.isNonNullable(t)?t:ot(e.map(({track:o})=>o),{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,n=e.find(({track:o})=>o.id===a)?.representation;i.assertNonNullable(n,"Representations missing"),this.dash.startPlay(n,s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(s)}setVideoTrack(e){const t=this.representations$.getValue().find(({track:s})=>s.id===e)?.representation;i.assertNonNullable(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}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=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&s===N.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(je(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:i.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,s=[];for(const a of t){const n=a.name??a.index.toString(10),o=ut(a.name)??Fe(a.video),u=a.bitrate/1e3,d={...a.video};if(!o)continue;const c={id:n,quality:o,bitrate:u,size:d};s.push({track:c,representation:a})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map(({track:a})=>a)),this.videoState.getTransition()?.to===N.MANIFEST_READY&&this.videoState.setState(N.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,s=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),i.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case"bandwidth":{const{size:t,duration:s}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,s);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(n)};`}),s===exports.PlaybackState.STOPPED){e!==N.STOPPED&&(this.videoState.startTransitionTo(N.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(N.STOPPED));return}if(!t){if(Li.includes(e)){const o=this.params.desiredState.videoTrack.getTransition()?.to;i.isNonNullable(o)&&this.setVideoTrack(o);const u=this.params.desiredState.autoVideoTrackSwitching.getTransition();u&&this.setAutoQuality(u.to)}if(a?.to!==exports.PlaybackState.PAUSED&&n.state===P.Requested&&Ii.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case N.STOPPED:this.videoState.startTransitionTo(N.MANIFEST_READY),this.dash.attachSource(je(this.params.source.url));return;case N.MANIFEST_READY:this.videoState.startTransitionTo(N.READY),this.prepare();break;case N.READY:if(s===exports.PlaybackState.PAUSED)this.videoState.setState(N.PAUSED);else if(s===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(N.PLAYING);const o=a?.from;o&&o===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(N.PAUSED)})}return;case N.PLAYING:s===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(N.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case N.PAUSED:s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(N.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(N.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return i.assertNever(e)}}}}var bs=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),s=e===null?exports.HttpConnectionType.HTTP1:e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:s,reused:a}},Oe=(r,e)=>{let t=0;for(let s=0;s<r.length;s++){const a=r.start(s)*1e3,n=r.end(s)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Bi=r=>{const e=document.createElement("a");return e.href=r,e.origin},Oi=r=>{const e=document.createElement("a");return e.href=r,e.host};class gs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,a,n,o){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=a,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(i.assertNonNullable(this._xhr),this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(s=>s.split(":").map(a=>a.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(Oi(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",t,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Et{_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(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const a=this._sourceBuffer.buffered;let n=0;for(let o=0,u=a.length;o<u;o++)n+=a.end(o)-a.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,a,n,o,u){this.abort(()=>{let d=0;const c=Date.now();let l=0,h=0,f=0;const S=m=>{a(Et._str2ua(m.substr(d))),d=m.length};let p=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(p=Qe(p)),this._lastXhr=new gs(p,e.failoverHosts,m=>{this._lastXhr=void 0,S(m);const b=Date.now()-c;this._params.onBandwidthChange({size:m.length,duration:b,speed:8*m.length/(b/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n?.()},m=>{if(m.length-d>u&&S(m),h===0){h=Date.now();return}f=m.length-l;const b=Date.now()-h;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,l=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,b,v)=>this._params.onError(m,b,v))})}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(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=Et._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(){this._mediaSource.readyState==="open"&&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),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Mi{_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=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(u,d)=>{const c=u?parseFloat(u.replace(",",".")):NaN;return(isNaN(c)?0:c)*d},a=t.exec(e),n=a?.[1]==="-"?-1:1,o={years:s(a?.[2],n),months:s(a?.[3],n),weeks:s(a?.[4],n),days:s(a?.[5],n),hours:s(a?.[6],n),minutes:s(a?.[7],n),seconds:s(a?.[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Qe(s)),new gs(s,t,a=>{this.attachManifest(a,t,Bi(s))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(c,l)=>{const h=c.attributes.getNamedItem(l);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const u=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),c=>{const l=c.getElementsByTagName("SegmentBase")[0],h=l&&o(l,"indexRange").split("-"),f=l&&l.getElementsByTagName("Initialization")[0],S=f&&o(f,"range").split("-");if(!S||!h){const F=c.parentElement;if(F?.getAttribute("contentType")==="text"){const E=c.getAttribute("id")??void 0,y=(s?s+"/":"")+c.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,R=F.getAttribute("lang")??void 0;y&&d.push({id:E,url:y,language:R})}return}const p=.1,m=Number(c.attributes.getNamedItem("bandwidth")?.value),b=(s?s+"/":"")+c.getElementsByTagName("BaseURL")[0].childNodes[0].data;let v;const $=c.attributes.getNamedItem("frameRate")?.value??void 0;v=$?It($):void 0,u.push({width:Number(c.attributes.getNamedItem("width")?.value),height:Number(c.attributes.getNamedItem("height")?.value),bandwidth:m,baseURL:b,failoverHosts:t,indexFrom:Number(h[0]),indexTo:Number(h[1]),initFrom:Number(S[0]),initTo:Number(S[1]),codecs:c.attributes.getNamedItem("codecs")?.value??void 0,mimeType:c.attributes.getNamedItem("mimeType")?.value??void 0,fps:v,bufferSize:p*m/8,bufferLength:p,name:c.attributes.getNamedItem("okQuality")?.value??void 0,id:c.attributes.getNamedItem("id")?.value??void 0})}),u.length)this._representations=u;else{this._onDashCallback("error");return}d.forEach(({id:c,language:l,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),c&&f.setAttribute("id",c),l&&f.setAttribute("srclang",l),this._video.appendChild(f)}),this._representations.sort((c,l)=>l.bandwidth-c.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,a=>{let n=e.initTo-e.initFrom+1;if(!a.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(a.buffer,0,n);const o=new DataView(a.buffer);n+=12;const u=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),c=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const l=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<l;f+=1){const S=c+(o.getUint32(n,!1)&2147483647),p=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/u,toTime:p/u,fromOffset:c,toOffset:S-1}),c=S,d=p}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,a=>{this._params.onResponseHeaders(a),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let a,n;const o=()=>{const c=this._findRef(this._video.currentTime);if(!c||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const S=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),S)}const l=this._appendVector[String(c.fromTime)];l!==a&&(a=l,this._params.onRepresentationPlay(l));let h;if(this._findRef(c.toTime)){const S=this._buffer.getByTime(this._video.currentTime);if(!S){this._onDashCallback("buffering");return}h=S.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==S.to&&(n=S.to,window.setTimeout(()=>{try{const p=this._buffer.getNextWithGap(S);p&&(this._video.currentTime=p.from)}catch(p){throw this._params.onError("GapSyncError",`Seek Error ${String(p)}`,p),p}},h*1e3)))}},u=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(c){throw this._params.onError("LoopError",`Dash Loop exception ${String(c)}`,c),c}u()},250)},d=()=>{if(!this._stream)try{const c=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Et({mediaSource:s,sourceBuffer:c,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(c){throw this._params.onError("DashSourceOpen",`Source open exception ${String(c)}`,c),c}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||u(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const c=this._video&&this._video.played.length;c&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(c-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,a=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),u=Math.abs(this._video.currentTime-t),d=a||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||u<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,u)=>this._stream.append(o,u),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),a=this._findRef(this._video.currentTime);if(!s||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<s.to+n){const o=this._findRef(a.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(u,d)=>this._stream.remove(u,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(u,d)=>this._stream.remove(u,d)),this._loadRef(e,a.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 e=this._video.currentTime;(!this._stream||i.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let a=0;a<t.length;a++){const n=t[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!s||n.fromTime<s.fromTime)&&(s=n)}if(!s){const a=t[t.length-1];if(e>a.toTime)return a}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),a=this._video.buffered.end(t);if(e>s&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var L;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(L||(L={}));const Vi=[L.PAUSED,L.PLAYING];class Fi{videoState=new G(L.STOPPED);subscription=new i.Subscription;video;buffer;dash;representations$=new i.ValueSubject([]);currentRepresentation$=new i.ValueSubject(void 0);params;textTracksManager=new Se;elementSize$=new i.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new i.Subject,responseHeaders$:new i.Subject,manifestReady$:new i.Subject,representationPlay$:new i.Subject,error$:new i.Subject};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),i.merge(this.videoState.stateChangeStarted$.pipe(i.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(i.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=Ae(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ci(this.video),this.dash=new Mi({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:a,category:i.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"DashProvider",category:i.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:u})},a=()=>{const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:u},n=$e(this.video),o=(u,d)=>this.subscription.add(u.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(n.seeking$.subscribe(()=>{i.isNullable(this.params.desiredState.seekState.getState().state!==P.Applying)&&(this.videoState.getState()===L.PLAYING||this.videoState.getState()===L.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ue(this.video,t.isLooped,s)),this.subscription.add(ke(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),o(yt(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===L.READY&&this.videoState.setState(L.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(L.PLAYING),T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(L.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(u=>{this.buffer.fill(),e.currentBuffer$.next(u)},s)).add(this.dashLiteEvents.error$.pipe(i.map(({id:u,message:d,thrown:c})=>({id:`DashLite_${u}`,category:i.ErrorCategory.WTF,message:d,thrown:c}))).subscribe(this.params.output.error$)).add(i.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$,i.fromEvent(this.video,"progress")).pipe(i.map(()=>{const u=this.currentRepresentation$.getValue(),d=this.representations$.getValue(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.videoTrack.getState(),h=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),S=a();c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to);let p;if(!S&&i.isNonNullable(l))p=l;else{const m=Oe(this.video.buffered,this.video.currentTime*1e3),b=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(m/b,1);p=ot(d.map(({track:$})=>$),{container:f,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:v,playbackRate:this.video.playbackRate,current:d.find(({representation:$})=>$===u)?.track})?.id}return i.isNonNullable(p)?d.find(({track:m})=>m.id===p)?.representation:void 0}),i.filterChanged()).subscribe(this.currentRepresentation$,s)).add(i.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(i.filter(u=>u.to===L.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(i.filter(i.isNonNullable))}).pipe(i.once()).subscribe(()=>this.videoState.setState(L.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(i.filter(i.isNonNullable),i.filterChanged((u,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?u.height<=d.height:u===d)).subscribe(u=>{const d=Oe(this.video.buffered,this.video.currentTime*1e3),c=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||c<=.5||!a())&&(this.dash.setQualityByRepresentation(u,!0),this.params.output.hostname$.next(ae(u.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(u=>{const{type:d,reused:c}=bs(u);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(c)})).add(this.dashLiteEvents.idxRequestPing$.pipe(i.once(),i.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(u=>this.params.dependencies.throughputEstimator.addRawRtt(u))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(i.filter(i.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(i.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return i.assertNever(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const a=s.name??s.id??s.height.toString(10),n=(s.name&&ut(s.name))??Fe(s),o=s.bandwidth/1e3,u={width:s.width,height:s.height},d=s.fps;if(!n)continue;const c={id:a,quality:n,bitrate:o,size:u,fps:d};t.push({track:c,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map(({track:s})=>s)),this.videoState.setState(L.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:s})=>s===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return i.assertNonNullable(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState(L.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:i.ErrorCategory.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(n)};`}),s===exports.PlaybackState.STOPPED){e!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(L.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(a?.to!==exports.PlaybackState.PAUSED&&n.state===P.Requested&&Vi.includes(e)&&this.seek(n.position,n.forcePrecise),e){case L.STOPPED:this.videoState.startTransitionTo(L.MANIFEST_LOADED),this.prepare();return;case L.MANIFEST_LOADED:this.videoState.startTransitionTo(L.INITIAL_REPRESENTATION_SELECTED);return;case L.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(L.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case L.METADATA_LOADED:this.videoState.startTransitionTo(L.READY),this.dash.updateRefsForCurrentTime();return;case L.READY:s===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(L.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.PLAYING),this.playIfAllowed());return;case L.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(L.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case L.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(L.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return i.assertNever(e)}}}var ue;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(ue||(ue={}));var Tt;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Tt||(Tt={}));var ce;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(ce||(ce={}));var B;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(B||(B={}));var We;(function(r){r.MP4="mp4",r.WEBM="webm"})(We||(We={}));var Rt=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const Ui=(r,e={})=>{const s=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Hi=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",qt=Hi?Ui:window.requestIdleCallback;let ys=!1;try{ys=ps()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class qi{bufferFull$=new i.Subject;error$=new i.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?!1:new Promise(s=>{const a={operation:"append",data:e,signal:t,callback:s};this.queue.push(a),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:s,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let s;ys&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}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",category:i.ErrorCategory.VIDEO_PIPELINE,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){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:i.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:i.assertNever(t)}}}var Yt=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};const Es=new TextDecoder("ascii"),Ts=r=>{let e=0,t=r.getUint32(e);e+=4;const s=new DataView(r.buffer,r.byteOffset+e,4),a=Es.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,r.byteLength)-e,o=new DataView(r.buffer,r.byteOffset+e,n);return{id:a,size:t,contents:o}},Yi=r=>Es.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Gi=(r,e,t)=>{const s=Ts(r),a=[];let n=0;const o=()=>{const m=s.contents.getUint32(n);return n+=4,m};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const c=o(),l=o(),h=o(),f=o()&4294967295;let S=l/c*1e3,p=(t?t.to+1:r.byteOffset+r.byteLength)+h;for(let m=0;m<f;m++){const b=o(),v=b>>>31,$=b<<1>>>1,F=o();if(o(),v!==0)throw new Error("Unsupported multilevel sidx");const E=F/c*1e3;a.push({status:B.NONE,time:{from:S,to:S+E},byte:{from:p,to:p+$-1}}),S+=E,p+=$}return a},ji=r=>{let e=0,t=!1,s=!1;for(;e<=r.byteLength&&!t;){const a=new DataView(r.buffer,r.byteOffset+e);try{const n=Ts(a);if(s||=n.id==="mdat",e+n.size<=r.byteLength)e+=n.size;else break}catch{t=!0}}return e>0&&e<=r.byteLength&&s?new DataView(r.buffer,r.byteOffset,e):null},zi={validateData:Yi,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Gi,parseFeedableSegmentChunk:ji};var g;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(g||(g={}));var k;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(k||(k={}));const Gt={[g.EBML]:{type:k.Master},[g.EBMLVersion]:{type:k.UnsignedInteger},[g.EBMLReadVersion]:{type:k.UnsignedInteger},[g.EBMLMaxIDLength]:{type:k.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[g.DocType]:{type:k.String},[g.DocTypeVersion]:{type:k.UnsignedInteger},[g.DocTypeReadVersion]:{type:k.UnsignedInteger},[g.Void]:{type:k.Binary},[g.Segment]:{type:k.Master},[g.SeekHead]:{type:k.Master},[g.Seek]:{type:k.Master},[g.SeekID]:{type:k.Binary},[g.SeekPosition]:{type:k.UnsignedInteger},[g.Info]:{type:k.Master},[g.TimestampScale]:{type:k.UnsignedInteger},[g.Duration]:{type:k.Float},[g.Tracks]:{type:k.Master},[g.Chapters]:{type:k.Master},[g.Cluster]:{type:k.Master},[g.Timestamp]:{type:k.UnsignedInteger},[g.SilentTracks]:{type:k.Master},[g.SilentTrackNumber]:{type:k.UnsignedInteger},[g.Position]:{type:k.UnsignedInteger},[g.PrevSize]:{type:k.UnsignedInteger},[g.SimpleBlock]:{type:k.Binary},[g.BlockGroup]:{type:k.Master},[g.EncryptedBlock]:{type:k.Binary},[g.Attachments]:{type:k.Master},[g.Tags]:{type:k.Master},[g.Cues]:{type:k.Master},[g.CuePoint]:{type:k.Master},[g.CueTime]:{type:k.UnsignedInteger},[g.CueTrackPositions]:{type:k.Master},[g.CueTrack]:{type:k.UnsignedInteger},[g.CueClusterPosition]:{type:k.UnsignedInteger},[g.CueRelativePosition]:{type:k.UnsignedInteger},[g.CueDuration]:{type:k.UnsignedInteger},[g.CueBlockNumber]:{type:k.UnsignedInteger},[g.CueCodecState]:{type:k.UnsignedInteger},[g.CueReference]:{type:k.Master},[g.CueRefTime]:{type:k.UnsignedInteger}},vs=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=vt(r,t),a=s in Gt,n=a?Gt[s].type:k.Binary,o=r.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(r.buffer,r.byteOffset+t+1,u-1),c=o&255>>u,l=vt(d),h=c*2**((u-1)*8)+l,f=t+u;let S;return f+h>r.byteLength?S=new DataView(r.buffer,r.byteOffset+f):S=new DataView(r.buffer,r.byteOffset+f,h),{tag:a?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:S,valueSize:h}},vt=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ve=(r,e)=>{switch(e){case k.SignedInteger:return r.getInt8(0);case k.UnsignedInteger:return vt(r);case k.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(r);case k.UTF8:return new TextDecoder("utf-8").decode(r);case k.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case k.Master:return r;case k.Binary:return r;default:i.assertNever(e)}},ct=(r,e)=>{let t=0;for(;t<r.byteLength;){const s=new DataView(r.buffer,r.byteOffset+t),a=vs(s);if(!e(a))return;a.type===k.Master&&ct(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},Qi=r=>{if(r.getUint32(0)!==g.EBML)return!1;let e,t,s;const a=vs(r);return ct(a.value,({tag:n,type:o,value:u})=>(n===g.EBMLReadVersion?e=ve(u,o):n===g.DocType?t=ve(u,o):n===g.DocTypeReadVersion&&(s=ve(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},ks=[g.Info,g.SeekHead,g.Tracks,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],Wi=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],Ji=r=>{let e,t,s,a,n=!1,o=!1,u=!1,d,c;return ct(r,({tag:l,type:h,value:f,valueSize:S})=>{if(l===g.SeekID){const p=ve(f,h);c=vt(p)}else l!==g.SeekPosition&&(c=void 0);return l===g.Segment?(e=f.byteOffset,t=f.byteOffset+S):l===g.Info?n=!0:l===g.SeekHead?o=!0:l===g.TimestampScale?s=ve(f,h):l===g.Duration?a=ve(f,h):l===g.SeekPosition&&c===g.Cues?d=ve(f,h):n&&o&&ks.includes(l)&&(u=!0),!u}),i.assertNonNullable(e,"Failed to parse webm Segment start"),i.assertNonNullable(t,"Failed to parse webm Segment end"),i.assertNonNullable(a,"Failed to parse webm Segment duration"),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:d}},Ki=r=>{if(i.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Xi=(r,e)=>{let t=!1,s=!1;const a=u=>i.isNonNullable(u.time)&&i.isNonNullable(u.position),n=[];let o;return ct(r,({tag:u,type:d,value:c})=>{switch(u){case g.Cues:t=!0;break;case g.CuePoint:o&&a(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=ve(c,d));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=ve(c,d));break;default:t&&ks.includes(u)&&(s=!0)}return!(t&&s)}),o&&a(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:l}=u,h=n[d+1];return{status:B.NONE,time:{from:c,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},Zi=r=>{let e=0,t=!1;try{ct(r,s=>s.tag===g.Cluster?s.tagSize<=r.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Wi.includes(s.tag)?(e+s.tagSize<=r.byteLength&&(e+=s.tagSize,t||=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(s.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},ea={validateData:Qi,parseInit:Ji,getIndexRange:Ki,parseSegments:Xi,parseFeedableSegmentChunk:Zi};class jt{onLastSegment$=new i.ValueSubject(!1);fullyBuffered$=new i.ValueSubject(!1);playingRepresentation$=new i.ValueSubject(void 0);error$=new i.Subject;gaps=[];subscription=new i.Subscription;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Me;destroyAbortController=new Me;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;constructor(e,t,s,a,{fetcher:n,tuning:o,getCurrentPosition:u,compatibilityMode:d=!1}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.container=s,s){case We.MP4:this.containerParser=zi;break;case We.WEBM:this.containerParser=ea;break;default:i.assertNever(s)}this.initData=new Map(a.map(c=>[c.id,null])),this.segments=new Map,this.representations=new Map(a.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=i.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);i.assertNonNullable(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new qi(this.sourceBuffer),this.subscription.add(i.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:i.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(i.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:i.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,Yt(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const s=this.initData.get(t.id),a=this.segments.get(t.id);if(i.assertNonNullable(s,"No init buffer for starting representation"),i.assertNonNullable(a,"No segments for starting representation"),!(s instanceof ArrayBuffer))return;let n=0;for(const o of a)o.time.from-n>0&&this.gaps.push({representation:t.id,from:n,to:o.time.from}),n=o.time.to;i.isNonNullable(t.duration)&&t.duration-n>0&&this.gaps.push({representation:t.id,from:n,to:t.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=i.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);i.assertNonNullable(t,`No such representation ${e}`);let s=this.initData.get(e);if(i.isNullable(s)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();i.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 Me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(i.isNullable(e)||i.isNullable(this.downloadingRepresentationId)||i.isNullable(this.playingRepresentationId)||i.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(i.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const a=s.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Oe(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&l>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Yt(this.sourceBuffer.buffered)>=this.bufferLimit){const c=Oe(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<l);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(s,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(u.includes(a))c="high";else{const l=u.at(0);l&&l.time.from-a.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===B.FED&&!u.length&&Oe(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=s.at(-1);d&&d.status===B.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const s=this.segments.get(t);return s?s.find(n=>n.time.from<=e&&n.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(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){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const a=e.findIndex(({status:h,time:{from:f,to:S}},p)=>{const m=f<=s&&S>=s,b=f>s||m||p===0&&s===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),$=this.preloadOnly&&f<=s+v||S<=s+v;return(h===B.NONE||h===B.PARTIALLY_EJECTED&&b&&$&&this.sourceBuffer&&!Rt(this.sourceBuffer.buffered,s))&&b&&$});if(a===-1)return[];if(t!==ce.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=c||u<=l);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===B.NONE||f.status===B.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,s="auto"){if(!e.length)return;let a,n,o=e;const{type:u}=t.segmentReference;switch(u){case ce.BYTE_RANGE:{a=t.segmentReference.url,n={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case ce.TEMPLATE:{const c=e.at(0);a=new URL(c.url,t.segmentReference.baseUrl).toString(),o=[c];break}default:i.assertNever(u)}for(const c of o)c.status=B.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await i.abortable(d,async function*(){const c=i.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),d.aborted))for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);return void this.fetcher.fetch(a,{range:n,onProgress:(c,l)=>{if(!d.aborted)try{this.onSomeDataLoaded(c,t.id,n?n.from:0,l,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:i.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,c=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(c)})}onSegmentDownloadError(e){let t=!1;const s=this.getCurrentPosition();this.sourceBuffer&&i.isNonNullable(s)&&(t=Oe(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:i.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},u=h=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=B.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const S of this.segments.get(f.id)??[])S.status===B.FED&&S.time.from===h.segment.time.from&&S.time.to===h.segment.time.to&&(S.status=B.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const c=d.segmentReference.type,l=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,S=c===ce.BYTE_RANGE,p=S?f.byte.to-f.byte.from+1:l;if(h.representationId!==t||!(!S||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const b=S?f.byte.from-s:0,v=S?f.byte.to-s:e.byteLength,$=b<a,F=v<=a;if(f.status===B.DOWNLOADING&&$&&F){f.status=B.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+b,p);this.sourceBufferTaskQueue.append(E,n).then(y=>y&&!n.aborted?u(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&$&&(h.loadedBytes=Math.min(p,a-b),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+h.feedingBytes,h.loadedBytes-h.feedingBytes),y=h.loadedBytes===p?E:this.containerParser.parseFeedableSegmentChunk(E);y?.byteLength&&(f.status=B.PARTIALLY_FED,h.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,n).then(R=>{if(n.aborted)o();else if(R)h.fedBytes+=y.byteLength,h.fedBytes===p&&u(h);else{if(h.feedingBytes<p)return;o()}}))}}}abortSegment(e){e.status===B.PARTIALLY_FED||e.status===B.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=B.NONE),e.status=B.PARTIALLY_EJECTED):e.status=B.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[a,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=qt(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?i.abortable(this.destroyAbortController.signal,async function*(){const u=i.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(u=>{if(!u)return;const{dataView:d,segments:c}=u,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:i.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||i.isNullable(e)||this.sourceBuffer.updating)return!1;let a=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const l="size"in c?c.size??0:c.byte.to-c.byte.from;a+=l};for(const c of this.segments.values())for(const l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;l.status===B.FED&&d(l)}if(u=isFinite(n)&&isFinite(o),!u){a=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;l.status===B.FED&&d(l)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const l=this.sourceBuffer.buffered.start(c)*1e3,h=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const S of f)if(S.status===B.NONE&&Math.round(S.time.from)<=Math.round(l)&&Math.round(S.time.to)>=Math.round(h)){n=l,o=h;break}}if(u=isFinite(n)&&isFinite(o),!u&&s){a=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const h of l)h.time.from>e+c&&h.status===B.FED&&d(h)}return u=isFinite(n)&&isFinite(o),u?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")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 a={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&u>=s.time.to){a=void 0;break}u>s.time.from&&u<s.time.to&&(a.from=u),o<s.time.to&&o>s.time.from&&(a.to=o)}}a&&a.to-a.from>=1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=qt(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:i.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(i.isNullable(this.sourceBuffer)||i.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const a=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:a,to:n})}const t=1;for(const s of this.segments.values())for(const a of s){const{status:n}=a;if(n!==B.FED&&n!==B.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),u=Math.ceil(a.time.to),d=e.some(l=>l.from-t<=o&&l.to+t>=u),c=e.filter(l=>o>=l.from-t&&o<=l.to+t||u>=l.from-t&&u<=l.to+t);d||(c.length===1?a.status=B.PARTIALLY_EJECTED:a.status=B.NONE)}}}var Ye;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Ye||(Ye={}));class ta{throughputEstimator;requestQuic;lastConnectionType$=new i.ValueSubject(void 0);lastConnectionReused$=new i.ValueSubject(void 0);lastRequestFirstBytes$=new i.ValueSubject(void 0);abortAllController=new Me;subscription=new i.Subscription;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=bs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=i.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Qe(t));const s=yield ze(t,{signal:this.abortAllController.signal}).catch(st);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=i.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Ye.HEADER:Ye.PARAM,range:s,onProgress:a,priority:n="auto",signal:o,measureThroughput:u=!0}={}){let d=e;const c=new Headers;if(s)switch(t){case Ye.HEADER:{c.append("Range",`bytes=${s.from}-${s.to}`);break}case Ye.PARAM:{const C=new URL(d,location.href);C.searchParams.append("bytes",`${s.from}-${s.to}`),d=C.toString();break}default:i.assertNever(t)}this.requestQuic&&(d=Qe(d));let l=this.abortAllController.signal;if(o){const C=new Me;if(this.subscription.add(i.merge(i.fromEvent(this.abortAllController.signal,"abort"),i.fromEvent(o,"abort")).subscribe(()=>{try{C.abort()}catch(M){st(M)}})),this.abortAllController.signal.aborted||o.aborted)try{C.abort()}catch(M){st(M)}l=C.signal}const h=i.now(),f=yield ze(d,{priority:n,headers:c,signal:l}).catch(st),S=i.now();if(this.throughputEstimator?.addRawRtt(S-h),!f)return null;if(!f.ok||!f.body)return Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const p=parseInt(f.headers.get("Content-Length")??"",10)||s&&s.to-s.from+1||NaN;if(!p){const C=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(C.byteLength,i.now()-S),a?.(new DataView(C),C.byteLength),C}if(!a&&!u)return f.arrayBuffer();const[m,b]=f.body.tee(),v=m.getReader();u&&this.throughputEstimator?.trackStream(b);let $=0;const F=new ArrayBuffer(p),E=new Uint8Array(F),y=new DataView(F);let R=!1;const _=C=>{R=!0,st(C)},q=i.abortable(l,async function*({done:C,value:M}){$===0&&this.lastRequestFirstBytes$.next(i.now()-h),!l.aborted&&(C?a?.(y,$):M&&(E.set(M,$),$+=M.byteLength,a?.(y,$),yield v?.read().then(q,_)))}.bind(this));return yield v?.read().then(q,_),R?null:F}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:a}=e;switch(a){case ce.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case ce.TEMPLATE:return await this.fetchTemplateRepresentation(e,s)??null;default:i.assertNever(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=i.abortable(this.abortAllController.signal,async function*(e,t,s){if(e.type!==ce.BYTE_RANGE)return null;const{from:a,to:n}=e.initRange;let o=a,u=n,d=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,a),u=Math.max(l,n))),o=Math.min(o,0);const h=yield this.fetch(e.url,{range:{from:o,to:u},priority:s,measureThroughput:!1});if(!h)return null;const f=new DataView(h,a-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const S=t.parseInit(f),p=e.indexRange??t.getIndexRange(S);if(!p)throw new ReferenceError("No way to load representation index");let m;if(d)m=new DataView(h,p.from-o,p.to-p.from+1);else{const v=yield this.fetch(e.url,{range:p,priority:s,measureThroughput:!1});if(!v)return null;m=new DataView(v)}const b=t.parseSegments(m,S,p);return{dataView:new DataView(h),segments:b}}.bind(this));fetchTemplateRepresentation=i.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==ce.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(s,{priority:t,measureThroughput:!1});return a?{segments:e.segments.map(o=>({...o,status:B.NONE,size:void 0})),dataView:new DataView(a)}:null}.bind(this))}const st=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},zt=r=>{if(!r.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},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(r),a=s?.[1]==="-"?-1:1,n={days:e(s?.[5],a),hours:e(s?.[6],a),minutes:e(s?.[7],a),seconds:e(s?.[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Pt=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(s)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>i.isNullable(n)?u:i.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},sa=(r,e)=>{const s=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},n=s.children[0],o=n.getElementsByTagName("Period")[0],u=o.children;let d;const c=n.getAttribute("mediaPresentationDuration"),l=o.getAttribute("duration");if(c)d=zt(c);else if(l){const p=zt(l);i.isNonNullable(p)&&(d=p)}let h=0;const f=n.getAttribute("profiles")?.split(",")??[],S=f.includes(Tt.WEBM_AS_IN_FFMPEG)||f.includes(Tt.WEBM_AS_IN_SPEC)?We.WEBM:We.MP4;for(const p of u){const m=p.getAttribute("mimeType"),b=p.getAttribute("codecs"),v=p.getAttribute("contentType")??m?.split("/")[0],$=p.getAttribute("profiles")?.split(",")??[],F=p.querySelectorAll("Representation"),E=p.querySelector("SegmentTemplate");if(v!=="text")for(const y of F){const R=y.getAttribute("mimeType")??m,_=y.getAttribute("codecs")??b??"",q=y.getAttribute("contentType")??R?.split("/")[0]??v,C=p.getAttribute("profiles")?.split(",")??[],M=parseInt(y.getAttribute("width")??"",10),j=parseInt(y.getAttribute("height")??"",10),O=parseInt(y.getAttribute("bandwidth")??"",10)/1e3,J=y.getAttribute("frameRate")??"",fe=y.getAttribute("quality")??void 0,we=J?It(J):void 0,A=y.getAttribute("id")??(h++).toString(10),V=q==="video"?`${j}p`:q==="audio"?`${O}Kbps`:_,W=`${A}@${V}`,X=y.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(X,e).toString(),Ne=[...f,...$,...C];let Je;const dt=y.querySelector("SegmentBase"),I=y.querySelector("SegmentTemplate")??E;if(dt){const Z=y.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[te,be]=Z.split("-").map(xe=>parseInt(xe,10)),ge={from:te,to:be},le=y.querySelector("SegmentBase")?.getAttribute("indexRange"),[De,Re]=le?le.split("-").map(xe=>parseInt(xe,10)):[],_e=le?{from:De,to:Re}:void 0;Je={type:ce.BYTE_RANGE,url:ie,initRange:ge,indexRange:_e}}else if(I){const Z={representationId:y.getAttribute("id")??void 0,bandwidth:y.getAttribute("bandwidth")??void 0},te=parseInt(I.getAttribute("timescale")??"",10),be=I.getAttribute("initialization")??"",ge=I.getAttribute("media"),le=parseInt(I.getAttribute("startNumber")??"",10)??1,De=Pt(be,Z);if(!ge)throw new ReferenceError("No media attribute in SegmentTemplate");const Re=I.querySelectorAll("SegmentTimeline S")??[],_e=[];if(Re.length){let xe=le,Be=0;for(const Ke of Re){const He=parseInt(Ke.getAttribute("d")??"",10)*1e3,Xe=parseInt(Ke.getAttribute("r")??"",10)||0,Ze=parseInt(Ke.getAttribute("t")??"",10)??void 0;for(let xt=0;xt<Xe+1;xt++){const Ds=Pt(ge,{...Z,segmentNumber:xe.toString(10),segmentTime:Ze.toString(10)}),Rs=Ze?Ze/te:Be;Be+=He/te;const _s=Be;xe++,_e.push({time:{from:Rs,to:_s},url:Ds})}}}else if(i.isNonNullable(d)){const Be=parseInt(I.getAttribute("duration")??"",10)/te*1e3,Ke=Math.ceil(d/Be);let He=0;for(let Xe=1;Xe<Ke;Xe++){const Ze=Pt(ge,{...Z,segmentNumber:Xe.toString(10),segmentTime:He.toString(10)});_e.push({time:{from:He,to:He+Be},url:Ze}),He+=Be}}Je={type:ce.TEMPLATE,baseUrl:ie,initUrl:De,segments:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!q||!R)continue;const ee={video:ue.VIDEO,audio:ue.AUDIO,text:ue.TEXT}[q];ee&&a[ee].push({id:W,kind:ee,segmentReference:Je,profiles:Ne,duration:d,bitrate:O,mime:R,codecs:_,width:M,height:j,fps:we,quality:fe})}}return{duration:d,container:S,representations:a}},ia=["timeupdate","progress","play","seeked","stalled","waiting"];var oe;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(oe||(oe={}));let aa=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new i.Subscription;fetcher;state$=new G(oe.NONE);currentVideoRepresentation$=new i.ValueSubject(void 0);error$=new i.Subject;lastConnectionType$=new i.ValueSubject(void 0);lastConnectionReused$=new i.ValueSubject(void 0);lastRequestFirstBytes$=new i.ValueSubject(void 0);forceEnded$=new i.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Me;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ta({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=i.abortable(this.destroyController.signal,async function*(e,t){this.element=e,this.state$.startTransitionTo(oe.MANIFEST_READY);const s=yield this.fetcher.fetchManifest(t).catch(o=>this.error$.next({id:"LoadManifest",category:i.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o}));if(!s)return;let a;try{a=sa(s??"",t)}catch(o){this.error$.next({id:"ManifestParsing",category:i.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return;const n=({mime:o,codecs:u})=>Boolean(e.canPlayType?.(o)&&window.MediaSource?.isTypeSupported?.(`${o}; codecs="${u}"`));this.manifest={...a,representations:Object.fromEntries(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(oe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:i.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));initRepresentations=i.abortable(this.destroyController.signal,async function*(e,t){i.assertNonNullable(this.manifest),i.assertNonNullable(this.element),this.state$.startTransitionTo(oe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new jt(ue.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],i.isNonNullable(t)&&(this.audioBufferManager=new jt(ue.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=i.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(i.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=i.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(i.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(i.merge(this.forceEnded$,i.combine({allBuffersFull:a,someBufferEnded:n}).pipe(i.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(o=>!o.updating))try{this.source?.endOfStream()}catch(o){this.error$.next({id:"EndOfStream",category:i.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.subscription.add(i.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),i.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&i.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(oe.REPRESENTATIOS_READY)}.bind(this));initBuffer(){i.assertNonNullable(this.element),this.state$.setState(oe.RUNNING),this.subscription.add(i.merge(...ia.map(e=>i.fromEvent(this.element,e)),i.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:i.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(i.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(i.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Rt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[ue.VIDEO]:this.videoBufferManager,[ue.AUDIO]:this.audioBufferManager,[ue.TEXT]:null}[e]?.switchTo(t)}seek(e,t){i.assertNonNullable(this.element),i.assertNonNullable(this.videoBufferManager);let s;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?s=e:s=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Rt(this.element.buffered,s)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(s),this.audioBufferManager?.maintain(s),this.element.currentTime=s/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(oe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=i.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:i.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=e&&a.to>e&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?t.push(1/0):t.push(a.to));if(t.length){const s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var z;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(z||(z={}));const ra=({id:r,width:e,height:t,bitrate:s,fps:a,quality:n})=>{const o=(n?ut(n):void 0)??Fe({width:e,height:t});return o&&{id:r,quality:o,bitrate:s,size:{width:e,height:t},fps:a}},na=({id:r,bitrate:e})=>({id:r,bitrate:e}),oa=(r,e,t)=>{const s=e.indexOf(t);return r.at(Math.round(r.length*s/e.length))??r.at(-1)};class ua{subscription=new i.Subscription;videoState=new G(z.STOPPED);video;player;params;elementSize$=new i.ValueSubject(void 0);textTracksManager=new Se;videoTracks=[];audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new bi;constructor(e){this.params=e,this.video=Ae(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new aa({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=$e(this.video),a=c=>{e.error$.next({id:"DashVKProvider",category:i.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:c})},n=(c,l)=>this.subscription.add(c.subscribe(l,a));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(i.filter(i.isNonNullable),i.once(),i.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ue(this.video,t.isLooped,a)),this.subscription.add(ke(this.video,t.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ie(this.video,t.playbackRate,s.playbackRateState$,a)),n(yt(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},a)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===oe.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const l=this.player.getRepresentations();i.assertNonNullable(l,"Manifest not loaded or empty");const h=Array.from(l.audio).sort((p,m)=>m.bitrate-p.bitrate),f=Array.from(l.video).sort((p,m)=>m.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const m=na(p);m&&this.audioTracks.push({track:m,representation:p})}for(const p of f){const m=ra(p);if(m){this.videoTracks.push({track:m,representation:p});const b=!this.params.tuning.isAudioDisabled&&oa(h,f,p);b&&this.audioRepresentations.set(p.id,b)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const S=this.selectVideoRepresentation();i.assertNonNullable(S),this.player.initRepresentations(S.id,this.audioRepresentations.get(S.id)?.id)}else c===oe.REPRESENTATIOS_READY&&(this.videoState.setState(z.READY),this.player.initBuffer())},a));const o=c=>e.error$.next({id:"RepresentationSwitch",category:i.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(i.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,i.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),l=this.player.state$.getTransition();if(c!==oe.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ue.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ue.AUDIO,f.id).catch(o)}},a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(i.filterChanged(),i.map(c=>c&&this.videoTracks.find(({representation:{id:l}})=>l===c)?.track)).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(i.map(({to:c})=>c===exports.PlaybackState.READY),i.filterChanged());this.subscription.add(i.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(i.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=i.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),s=this.videoTracks.find(({track:{id:h}})=>h===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),n=Oe(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(s&&!e?this.audioRepresentations.get(s.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),c=ot(this.videoTracks.map(({track:h})=>h),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),l=e?c??s:s??c;return l&&this.videoTracks.find(({track:h})=>h===l)?.representation}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===P.Requested&&s?.to!==exports.PlaybackState.PAUSED&&e!==z.STOPPED&&t!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),t===exports.PlaybackState.STOPPED){e!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.player.stop(),this.video.removeAttribute("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(z.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();return;case z.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.READY&&T(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case z.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return i.assertNever(e)}}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:i.ErrorCategory.DOM,thrown:e}))}}const ca=5e3,ye={};var x;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(x||(x={}));const pt=(r,e)=>new i.Observable(t=>{const s=(a,n)=>t.next(n);return r.on(e,s),()=>r.off(e,s)});class da{subscription=new i.Subscription;videoState=new G(x.INITIALIZING);video;params;hls;textTracksManager=new Se;trackLevels=new Map;constructor(e){this.video=Ae(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:i.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},s=window.setTimeout(()=>t("timeout"),ca);import("hls.js").then(a=>{e||(ye.Hls=a.default,ye.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){i.assertNonNullable(ye.Hls,"hls.js not loaded"),this.hls=new ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){i.assertNonNullable(ye.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=c=>{t.error$.next({id:"HlsJsProvider",category:i.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},a=$e(this.video),n=(c,l)=>this.subscription.add(c.subscribe(l,s));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(Ue(this.video,e.isLooped,s)),this.subscription.add(ke(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,a.playbackRateState$,s)),this.subscription.add(pt(this.hls,ye.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:i.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(x.PLAYING),T(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED),T(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===x.READY&&this.videoState.setState(x.READY),this.videoState.getState()===x.PLAYING&&this.playIfAllowed()},s)),n(pt(this.hls,ye.Events.MANIFEST_PARSED).pipe(i.map(({levels:c})=>c.reduce((l,h)=>{const f=h.name||h.height.toString(10),{width:S,height:p}=h,m=ut(h.attrs.QUALITY??"")??Fe({width:S,height:p});if(!m)return l;const b=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,v={id:f.toString(),quality:m,bitrate:h.bitrate/1e3,size:{width:S,height:p},fps:b};return this.trackLevels.set(f,{track:v,level:h}),l.push(v),l},[]))),t.availableVideoTracks$),n(pt(this.hls,ye.Events.LEVEL_LOADING).pipe(i.map(({url:c})=>ae(c))),t.hostname$),this.subscription.add(me(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:s}));const o=c=>Array.from(this.trackLevels.values()).find(({level:l})=>l===c)?.track,u=pt(this.hls,ye.Events.LEVEL_SWITCHED).pipe(i.map(({level:c})=>o(this.hls.levels[c])));u.pipe(i.filter(i.isNonNullable)).subscribe(t.currentVideoTrack$,s),this.subscription.add(me(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel])?.id,c=>{if(i.isNullable(c))return;const l=this.trackLevels.get(c)?.level;if(!l)return;const h=this.hls.levels.indexOf(l),f=this.hls.currentLevel,S=this.hls.levels[f];!S||l.bitrate>S.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:u.pipe(i.map(c=>c?.id)),onError:s})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=i.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!==x.INITIALIZING)switch(s?.to!==exports.PlaybackState.PAUSED&&a.state===P.Requested&&this.seek(a.position),t){case exports.PlaybackState.STOPPED:switch(e){case x.STOPPED:break;case x.READY:case x.PLAYING:case x.PAUSED:this.stop();break;default:i.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case x.STOPPED:this.prepare();break;case x.READY:case x.PLAYING:case x.PAUSED:break;default:i.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case x.PLAYING:break;case x.STOPPED:this.prepare();break;case x.READY:case x.PAUSED:this.playIfAllowed();break;default:i.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case x.PAUSED:break;case x.STOPPED:this.prepare();break;case x.READY:this.videoState.setState(x.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case x.PLAYING:this.pause();break;default:i.assertNever(e)}break;default:i.assertNever(t)}};prepare(){this.videoState.startTransitionTo(x.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(x.PLAYING),await Le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:i.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(x.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(x.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.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Qt="X-Playback-Duration";var Wt=async r=>{const e=await ze(r,{method:"HEAD"});return e.headers.has(Qt)?parseInt(e.headers.get(Qt),10):void 0};const la=r=>{let e=null;if(r.QUALITY&&(e=ut(r.QUALITY)),!e&&r.RESOLUTION){const[t,s]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Fe({width:t,height:s})}return e??null},As=async(r,e=r)=>{const a=(await(await ze(r)).text()).split(`
|
|
8
|
+
`),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const c=Object.fromEntries(d[1].split(",").map(b=>b.split("="))),l=c.QUALITY??`stream-${c.BANDWIDTH}`,h=la(c);let f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const S=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[b,v]=c.RESOLUTION.split("x").map($=>parseInt($,10));b&&v&&(p={width:b,height:v})}const m=new URL(a[++o],e).toString();h&&n.push({id:l,quality:h,url:m,bandwidth:f,size:p,fps:S})}return n};var U;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(U||(U={}));class ha{subscription=new i.Subscription;videoState=new G(U.STOPPED);video;params;textTracksManager=new Se;manifests$=new i.ValueSubject([]);maxSeekBackTime$;liveOffset=new Ct;manifestStartTime$=new i.ValueSubject(void 0);constructor(e){this.params=e,this.video=Ae(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]),As(je(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:i.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.maxSeekBackTime$=new i.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),a=t.getTransition(),n=a?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o)return;const u=s?"master":n;return s&&!a&&t.startTransitionTo("master"),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"HlsLiveProvider",category:i.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},a=$e(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,s));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(ke(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY),this.videoState.getState()===U.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(i.filterChanged(),i.map(u=>-u/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&i.isNonNullable(c.to)){const h=c.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(S=>S.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ae(f.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===U.CHANGING_MANIFEST&&this.videoState.setState(d.to),u&&u.state===P.Requested&&this.seek(u.position)},s)),this.subscription.add(a.loadedData$.subscribe(()=>{const u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},s)),this.subscription.add(i.combine({startTime:this.manifestStartTime$.pipe(i.filter(i.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:u,currentTime:d})=>this.params.output.liveTime$.next(u+d*1e3),s)),this.subscription.add(this.manifests$.pipe(i.map(u=>u.map(({id:d,quality:c,size:l,bandwidth:h,fps:f})=>({id:d,quality:c,size:l,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const o=i.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,i.observableFrom(["init"])).pipe(i.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}prepare(){const e=this.selectManifest();if(i.isNullable(e))return;const t=je(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Wt(t).then(s=>{if(!i.isNullable(s))this.maxSeekBackTime$.next(s);else{const a=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(i.isNullable(a)||!isFinite(a))try{ze(t).then(n=>n.text()).then(n=>{const o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n)?.[1];if(o){const u=new URL(o,t).toString();Wt(u).then(d=>{i.isNullable(d)||this.maxSeekBackTime$.next(d)})}})}catch{}}})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:i.ErrorCategory.DOM,thrown:e}))}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 e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===exports.PlaybackState.STOPPED){e!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(U.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(e===U.STOPPED){this.videoState.startTransitionTo(U.READY),this.prepare();return}if(a||n){const d=this.videoState.getState();this.videoState.setState(U.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),u.state===P.None&&this.params.desiredState.seekState.setState({state:P.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==exports.PlaybackState.PAUSED&&u.state===P.Requested){this.videoState.startTransitionTo(U.READY),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case U.READY:t===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed());return;case U.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(U.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())):s?.to===exports.PlaybackState.PAUSED&&(T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case U.CHANGING_MANIFEST:break;default:return i.assertNever(e)}}}var Y;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(Y||(Y={}));class fa{subscription=new i.Subscription;videoState=new G(Y.STOPPED);video;params;textTracksManager=new Se;manifests$=new i.ValueSubject([]);constructor(e){this.params=e,this.video=Ae(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.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),As(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:i.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),a=t.getTransition(),n=a?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o)return;const u=s?"master":n;return s&&!a&&t.startTransitionTo("master"),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"HlsProvider",category:i.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},a=$e(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ue(this.video,t.isLooped,s)),this.subscription.add(ke(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},s).add(a.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&i.isNonNullable(c.to)){const h=c.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(S=>S.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ae(f.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===P.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe(i.map(u=>u.map(({id:d,quality:c,size:l,bandwidth:h,fps:f})=>({id:d,quality:c,size:l,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const o=i.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}prepare(){const e=this.selectManifest();i.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:i.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===exports.PlaybackState.STOPPED){e!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.removeAttribute("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(Y.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(e===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(a||n){const d=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:c}=this.video;this.prepare(),u.state===P.None&&this.params.desiredState.seekState.setState({state:P.Requested,position:c*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&u.state===P.Requested&&this.seek(u.position),e){case Y.READY:t===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case Y.CHANGING_MANIFEST:break;default:return i.assertNever(e)}}}var Q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Q||(Q={}));class pa{subscription=new i.Subscription;videoState=new G(Q.STOPPED);video;trackUrls={};params;textTracksManager=new Se;constructor(e){this.params=e,this.video=Ae(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=u=>{e.error$.next({id:"MpegProvider",category:i.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},a=$e(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ue(this.video,t.isLooped,s)),this.subscription.add(ke(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,s)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&i.isNonNullable(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const o=i.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Pe(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();i.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];i.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Qe(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ae(t))}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:i.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.video.removeAttribute("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(Q.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(e===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===P.None&&this.params.desiredState.seekState.setState({state:P.Requested,position:u*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&o.state===P.Requested&&this.seek(o.position),e){case Q.READY:t===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return i.assertNever(e)}}}const Jt=["stun:videostun.mycdn.me:80"],ma=1e3,Sa=3,wt=()=>null;class ba{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=wt;externalStopCallback=wt;externalErrorCallback=wt;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(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}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(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}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);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Jt}]};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(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:i.ErrorCategory.WTF,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(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}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{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),ma)}normalizeOptions(e={}){const t={stunServerList:Jt,maxRetryNumber:Sa,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var H;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(H||(H={}));class ga{subscription;params;log;video;videoState=new G(H.STOPPED);liveStreamClient;maxSeekBackTime$=new i.ValueSubject(0);constructor(e){this.subscription=new i.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container),this.liveStreamClient=new ba(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.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Pe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"WebRTCLiveProvider",category:i.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};i.merge(this.videoState.stateChangeStarted$.pipe(i.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(i.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(o)}`})});const a=$e(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,s));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},s)).add(a.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING)},s)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ke(this.video,t.volume,a.volumeState$,s)).add(a.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case H.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case H.READY:break;case H.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case H.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return i.assertNever(o.to)}},s)).add(i.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,i.observableFrom(["init"])).pipe(i.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(H.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:i.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:i.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==H.STOPPED&&(this.videoState.startTransitionTo(H.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(H.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case H.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return i.assertNever(e)}}}class Kt{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var ya=()=>{const r=window.navigator;return r.userAgentData?r.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const $s=ya(),kt=document.createElement("video"),Ee={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(kt.canPlayType?.("application/x-mpegurl")||kt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},ne={mp4:Boolean(kt.canPlayType?.("video/mp4")),webm:Boolean(kt.canPlayType?.("video/webm")),cmaf:!0},Ce={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"'))},qe=(Ce.h264||Ce.h265)&&Ce.aac,$t=Ee.hls&&ne.mp4,Ea=Boolean(window.WebSocket),Ta=()=>Object.keys(Ce).filter(r=>Ce[r]),va=(r,e=!1)=>r.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Ee.mse&&ne.mp4&&qe;case exports.VideoFormat.DASH_SEP:return Ee.mse&&ne.mp4&&qe;case exports.VideoFormat.DASH_WEBM:return Ee.mse&&ne.webm&&Ce.vp9&&Ce.opus;case exports.VideoFormat.DASH_LIVE:return Ee.mse&&ne.mp4&&qe;case exports.VideoFormat.DASH_LIVE_CMAF:return Ee.mse&&ne.mp4&&qe&&ne.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Ee.mse&&ne.mp4&&qe;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return $t||e&&Ee.mse&&ne.mp4&&qe;case exports.VideoFormat.MPEG:return ne.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ee.webrtc&&Ea&&Ce.h264&&(ne.mp4||ne.webm);default:return i.assertNever(t)}}),ka=()=>$s?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:$t?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Aa=()=>$s?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:$t?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],Xt=r=>r?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var $a=r=>new i.Observable(e=>{const t=new i.Subscription,s=r.desiredPlaybackState$.stateChangeStarted$.pipe(i.map(({from:c,to:l})=>`${c}-${l}`)),a=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$,o=new i.Subject;let u=0,d="unknown";return t.add(s.subscribe(c=>{u&&window.clearTimeout(u),d=c,u=window.setTimeout(()=>o.next(c),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(u),d="provider change",u=0})),t.add(n.subscribe(()=>{u&&(window.clearTimeout(u),u=window.setTimeout(()=>o.next(d),r.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});const Zt={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Pa={cacheDuration:12e4},wa={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Na={maxPausedTime:3e4},es={maxPausedTime:3e4};class Da{current$=new i.ValueSubject({type:void 0});providerError$=new i.Subject;noAvailableProvidersError$=new i.Subject;providerOutput={position$:new i.ValueSubject(0),duration$:new i.ValueSubject(1/0),volume$:new i.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new i.ValueSubject(void 0),availableVideoTracks$:new i.ValueSubject([]),availableAudioTracks$:new i.ValueSubject([]),isAudioAvailable$:new i.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new i.ValueSubject(!1),currentBuffer$:new i.ValueSubject(void 0),isBuffering$:new i.ValueSubject(!0),error$:new i.Subject,willSeekEvent$:new i.Subject,seekedEvent$:new i.Subject,loopedEvent$:new i.Subject,endedEvent$:new i.Subject,firstBytesEvent$:new i.Subject,firstFrameEvent$:new i.Subject,canplay$:new i.Subject,isLive$:new i.ValueSubject(void 0),liveTime$:new i.ValueSubject(void 0),availableTextTracks$:new i.ValueSubject([]),currentTextTrack$:new i.ValueSubject(void 0),hostname$:new i.ValueSubject(void 0),httpConnectionType$:new i.ValueSubject(void 0),httpConnectionReused$:new i.ValueSubject(void 0),element$:new i.ValueSubject(void 0)};subscription=new i.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=va([...Aa(),...ka()],this.params.tuning.useHlsJs).filter(o=>i.isNonNullable(e.sources[o])),{formatsToAvoid:s}=this.params.tuning,a=s.length?[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:t;this.screenFormatsIterator=new Kt(a);const n=[...Xt(!0),...Xt(!1)];this.chromecastFormatsIterator=new Kt(n.filter(o=>i.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(i.isNullable(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:i.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}s?this.current$.next({type:t,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;i.assertNonNullable(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),a=s.state!==P.None;this.params.desiredState.seekState.setState({state:P.Requested,position:a?s.position:t,forcePrecise:a?s.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case re.SCREEN:return this.createScreenProvider(t);case re.CHROMECAST:return this.createChromecastProvider(t);default:return i.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:a}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new Fi({...o,source:u,config:Pa})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),this.params.tuning.useDashJs?new Ft({...o,source:u,format:e,config:es}):new ua({...o,source:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new Ft({...o,source:u,format:e,config:es})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),$t||!this.params.tuning.useHlsJs?new fa({...o,source:u}):new da({...o,source:u})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new ha({...o,source:u,config:Na})}case exports.VideoFormat.MPEG:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new pa({...o,source:u})}case exports.VideoFormat.DASH_LIVE:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new xi({...o,source:u,config:wa})}case exports.VideoFormat.WEB_RTC_LIVE:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new ga({container:s,source:u,desiredState:a,output:n,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 i.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:a,meta:n}=this.params,o=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return i.assertNonNullable(u),new Zs({connection:u,meta:n,container:s,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?re.CHROMECAST:re.SCREEN}chooseFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case re.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return i.assertNever(e)}}skipFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.next();case re.CHROMECAST:return this.chromecastFormatsIterator.next();default:return i.assertNever(e)}}handleNoFormatsError(e){switch(e){case re.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case re.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return i.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return Object.fromEntries(Object.entries(e).map(([a,n])=>[a,s(n)]))}initProviderErrorHandling(){const e=new i.Subscription;let t=!1,s=0;return e.add(i.merge(this.providerOutput.error$,$a({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Zt.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(i.filter(({type:a})=>a!==void 0))}).pipe(i.map(a=>({id:`ProviderHangup:${a}`,category:i.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(i.filter(({to:n})=>n===exports.PlaybackState.PLAYING),i.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{if(this.current$.getValue().destination===re.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=a.category===i.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=s<Zt.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var de;(function(r){r[r.LOCAL_STORAGE=0]="LOCAL_STORAGE",r[r.SESSION_STORAGE=1]="SESSION_STORAGE",r[r.RUNTIME=2]="RUNTIME"})(de||(de={}));const Ps=new Map;let Ve=de.RUNTIME;const Nt=`vk-videoplayer-dummy-key-${Math.random()}`,Ra=()=>{try{localStorage.setItem(Nt,"test"),localStorage.removeItem(Nt),Ve=de.LOCAL_STORAGE}catch(r){if(r instanceof DOMException||r instanceof TypeError)try{sessionStorage.getItem(Nt),Ve=de.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Ve=de.RUNTIME;else throw e}else throw r}};Ra();const _a=r=>{switch(Ve){case de.LOCAL_STORAGE:return localStorage.getItem(r)??void 0;case de.SESSION_STORAGE:return sessionStorage.getItem(r)??void 0;case de.RUNTIME:return Ps.get(r);default:i.assertNever(Ve)}},ts=(r,e)=>{switch(Ve){case de.LOCAL_STORAGE:try{localStorage.setItem(r,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case de.SESSION_STORAGE:try{sessionStorage.setItem(r,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case de.RUNTIME:return void Ps.set(r,e);default:i.assertNever(Ve)}},_t=(r,e,t)=>t*e+(1-t)*r,ws=(r,e)=>r.reduce((t,s)=>t+s,0)/e,Ca=(r,e,t,s)=>{let a=0,n=t;const o=ws(r,e),u=e<s?e:s;for(let d=0;d<u;d++)r[n]>o?a++:a--,n=(r.length+n-1)%r.length;return Math.abs(a)===u};class Ns{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new i.ValueSubject(e.initial),this.debounced$=new i.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new pe(`raw_${t}`),this.smoothedSeries$=new pe(`smoothed_${t}`),this.reportedSeries$=new pe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(i.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))}}class Ia extends Ns{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=_t(this.slow,e,this.params.emaAlphaSlow),this.fast=_t(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class La extends Ns{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ws(this.pastMeasures,this.takenMeasures);this.emaSmoothed=_t(this.emaSmoothed,e,this.params.emaAlpha);const s=Ca(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class ss{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Ia({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new La({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const xa=5e3,is="one_video_throughput",as="one_video_rtt",rt=window.navigator.connection,rs=()=>{const r=rt?.downlink;if(i.isNonNullable(r)&&r!==10)return r*1e3},ns=()=>{const r=rt?.rtt;if(i.isNonNullable(r)&&r!==3e3)return r},os=(r,e,t)=>{const s=t*8,a=s/r;return s/(a+e)};class nt{throughput;rtt;subscription=new i.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=nt.load(is)||(e.useBrowserEstimation?rs():void 0)||xa,s=nt.load(as)??(e.useBrowserEstimation?ns():void 0)??0;if(this.throughput$=new i.ValueSubject(t),this.rtt$=new i.ValueSubject(s),this.rttAdjustedThroughput$=new i.ValueSubject(os(t,s,e.rttPenaltyRequestSize)),this.throughput=ss.getSmoothedValue(t,-1,e),this.rtt=ss.getSmoothedValue(s,1,e),e.useBrowserEstimation){const a=()=>{const o=rs();o&&this.throughput.next(o);const u=ns();i.isNonNullable(u)&&this.rtt.next(u)};rt&&"onchange"in rt&&this.subscription.add(i.fromEvent(rt,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{ts(is,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{ts(as,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(i.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(i.map(({throughput:a,rtt:n})=>os(a,n,e.rttPenaltyRequestSize)),i.filter(a=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=i.now();const a=new i.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(i.fromEvent(e,"progress").pipe(i.once()).subscribe(n=>{t=n.loaded,s=i.now()}));break;case 1:case 0:a.add(i.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=i.now()}));break}a.add(i.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,u=i.now(),d=o-t,c=u-s;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let s=0;const a=i.now();let n=0,o=i.now();const u=c=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=async({done:c,value:l})=>{c?(this.addRawSpeed(s,i.now()-a,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&i.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,i.now()-o,this.concurrentDownloads.size),n=0,o=i.now()),await t?.read().then(d,u))};this.concurrentDownloads.add(e),t?.read().then(d,u)}addRawSpeed(e,t,s=1){if(nt.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){const t=_a(e);if(i.isNonNullable(t))return parseInt(t,10)??void 0}}const us={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},Ba=r=>{const e={};for(const t of Object.keys(us)){const s=us[t],a=r[t];Array.isArray(s)&&Array.isArray(a)?e[t]=a:typeof s=="object"&&typeof a=="object"?e[t]={...s,...a}:e[t]=a??s}return e};var Oa=({seekState:r,position$:e})=>i.merge(r.stateChangeEnded$.pipe(i.map(({to:t})=>t.state===P.None?void 0:(t.position??NaN)/1e3),i.filter(i.isNonNullable)),e.pipe(i.filter(()=>r.getState().state===P.None))),Ma=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return i.assertNonNullable(e,`Wrong container or containerId {${r.container}}`),e};const cs=({playbackState:r,seekState:e,playbackAbort$:t,looped$:s,position$:a})=>new i.Observable(n=>{let o;const u=r.transitionEnded$.pipe(i.filter(S=>(S.from===exports.PlaybackState.PAUSED||S.from===exports.PlaybackState.STOPPED)&&S.to===exports.PlaybackState.PLAYING)),d=r.stateChangeEnded$.pipe(i.filter(S=>S.from===exports.PlaybackState.PLAYING&&S.to===exports.PlaybackState.PAUSED)),c=e.stateChangeEnded$.pipe(i.filter(({to:S})=>S.state===P.Requested&&(r.getTransition()?.from??r.getState())===exports.PlaybackState.PLAYING)),l=e.stateChangeEnded$.pipe(i.filter(({from:S,to:p})=>S.state===P.Applying&&p.state===P.None&&(r.getTransition()?.from??r.getState())===exports.PlaybackState.PLAYING)),h=i.merge(u,l).pipe(i.map(()=>a.getValue()),i.filter(i.isNonNullable)),f=i.merge(i.merge(d,c,t),s).pipe(i.map(()=>a.getValue()),i.filter(i.isNonNullable));return new i.Subscription().add(h.subscribe(S=>{o=S})).add(f.subscribe(S=>{if(i.isNullable(o)||o===S)return;const p={from:o,to:S};o=void 0,n.next(p)}))});class Va{subscription=new i.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new i.Logger;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new G(exports.PlaybackState.STOPPED),seekState:new G({state:P.None}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({})};info={playbackState$:new i.ValueSubject(exports.PlaybackState.STOPPED),position$:new i.ValueSubject(0),duration$:new i.ValueSubject(1/0),muted$:new i.ValueSubject(!1),volume$:new i.ValueSubject(1),availableQualities$:new i.ValueSubject([]),availableQualitiesFps$:new i.ValueSubject({}),availableAudioTracks$:new i.ValueSubject([]),isAudioAvailable$:new i.ValueSubject(!0),currentQuality$:new i.ValueSubject(void 0),isAutoQualityEnabled$:new i.ValueSubject(!0),autoQualityLimitingAvailable$:new i.ValueSubject(!1),autoQualityLimits$:new i.ValueSubject({}),currentPlaybackRate$:new i.ValueSubject(1),currentBuffer$:new i.ValueSubject({start:0,end:0}),isBuffering$:new i.ValueSubject(!0),isStalled$:new i.ValueSubject(!1),isEnded$:new i.ValueSubject(!1),isLooped$:new i.ValueSubject(!1),isLive$:new i.ValueSubject(void 0),liveTime$:new i.ValueSubject(void 0),currentFormat$:new i.ValueSubject(void 0),availableTextTracks$:new i.ValueSubject([]),currentTextTrack$:new i.ValueSubject(void 0),throughputEstimation$:new i.ValueSubject(void 0),rttEstimation$:new i.ValueSubject(void 0),videoBitrate$:new i.ValueSubject(void 0),hostname$:new i.ValueSubject(void 0),httpConnectionType$:new i.ValueSubject(void 0),httpConnectionReused$:new i.ValueSubject(void 0),chromecastState$:new i.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new i.ValueSubject(void 0),intrinsicVideoSize$:new i.ValueSubject(void 0)};events={inited$:new i.Subject,started$:new i.Subject,willPause$:new i.Subject,willResume$:new i.Subject,willDestruct$:new i.Subject,watchCoverageRecord$:new i.Subject,watchCoverageLive$:new i.Subject,managedError$:new i.Subject,fatalError$:new i.Subject,ended$:new i.Subject,looped$:new i.Subject,seeked$:new i.Subject,willSeek$:new i.Subject,firstBytes$:new i.Subject,firstFrame$:new i.Subject,canplay$:new i.Subject,log$:new i.Subject};experimental={element$:new i.ValueSubject(void 0),enableDebugTelemetry$:new i.ValueSubject(!1),dumpTelemetry:pi};constructor(e={}){if(this.initLogs(),this.tuning=Ba(e),this.chromecastInitializer=new Hs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new nt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,a)=>{const n=Reflect.get(t,s,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(u){const d=o.map(h=>JSON.stringify(h,(f,S)=>{const p=typeof S;return["number","string","boolean"].includes(p)?S:S===null?null:`<${p}>`})),c=`Player.${String(s)}`,l=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:i.ErrorCategory.WTF,message:l,thrown:u}),u}}}})}initVideo(e){return this.config=e,this.domContainer=Ma(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Da({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}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:P.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){i.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(a=>a.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){i.assertNonNullable(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return(e===void 0||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(){i.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(i.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===P.None?void 0:t.position;return i.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:a})=>s||a||0,0),height:e.reduce((s,{height:a})=>s||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(i.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(i.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(i.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(i.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(i.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(i.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(i.filter(({from:e})=>e===exports.PlaybackState.STOPPED),i.once()).subscribe(()=>{this.initedAt=i.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(i.filter(()=>!this.isPlaybackStarted),i.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===P.Requested?this.desiredState.seekState.setState({...d,state:P.Applying}):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:i.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===P.Applying&&(this.desiredState.seekState.setState({state:P.None}),this.events.seeked$.next())})).add(e.current$.pipe(i.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(i.map(d=>d.destination),i.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(i.map(d=>d.map(({quality:c})=>c).sort((c,l)=>bt(c)?1:bt(l)?-1:mt(l,c)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const c={};for(const l of d)l.fps&&(c[l.quality]=l.fps);this.info.availableQualitiesFps$.next(c)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d?.quality),this.info.videoBitrate$.next(d?.bitrate)})).add(e.providerOutput.hostname$.pipe(i.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(i.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(i.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(i.map(d=>d?{start:d.from,end:d.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(i.map(d=>d.muted),i.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(i.map(d=>d.volume),i.filterChanged()).subscribe(this.info.volume$)).add(Oa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(i.merge(e.providerOutput.endedEvent$.pipe(i.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(i.mapTo(!1))).pipe(i.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(i.map(d=>({id:"NoProviders",category:i.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(i.once(),i.map(()=>i.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(i.once(),i.map(()=>i.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(i.once(),i.map(()=>i.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new i.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new i.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(i.filter(({to:d})=>d===exports.PlaybackState.PLAYING),i.once()).subscribe(()=>s.next(!1)));let a=0;const n=i.merge(e.providerOutput.isBuffering$,t,s).pipe(i.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),c=t.getValue()||s.getValue();return d&&!c}),i.filterChanged());this.subscription.add(n.subscribe(d=>{d?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))}));const o=new i.Subscription;this.subscription.add(o);const u=i.merge(i.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(i.filter(d=>Boolean(d?.provider))));e.providerOutput.isLive$.pipe(i.filterChanged()).subscribe(d=>{switch(i.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const c=new i.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>c.next(l&&Math.floor(l/1e3)))),o.add(cs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:u,looped$:this.events.looped$,position$:c}).pipe(i.map(({from:l,to:h})=>({start:l,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(cs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:u,position$:this.providerContainer.providerOutput.position$}).pipe(i.map(({from:c,to:l})=>({start:c,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(i.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d?.videoWidth,height:d?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d?.size?.width,height:d?.size?.height},{width:c?.videoWidth,height:c?.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(i.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new i.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(i.filterChanged((s,a)=>s.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(i.filter(s=>s.length>0),i.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=ot(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(i.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(i.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(i.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(i.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(i.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(i.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(i.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(i.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(i.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(i.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 e=this.providerContainer?.providerOutput;i.assertNonNullable(this.providerContainer),i.assertNonNullable(e),fi(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>hi(t)),this.providerContainer.current$.subscribe(({type:t})=>lt("provider",t)),e.duration$.subscribe(t=>lt("duration",t)),e.availableVideoTracks$.pipe(i.filter(t=>!!t.length),i.once()).subscribe(t=>lt("tracks",t)),this.events.fatalError$.subscribe(new pe("fatalError")),this.events.managedError$.subscribe(new pe("managedError")),e.position$.subscribe(new pe("position")),e.currentVideoTrack$.pipe(i.map(t=>t?.quality)).subscribe(new pe("quality")),this.info.currentBuffer$.subscribe(new pe("buffer")),e.isBuffering$.subscribe(new pe("isBuffering"))].forEach(t=>this.subscription.add(t)),lt("codecs",Ta())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:i.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(i.merge(i.fromEvent(document,"visibilitychange"),i.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!e?.released;a&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const Fa=`${Fs}@${Vs}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return i.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return i.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return i.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return i.ValueSubject}});exports.Player=Va;exports.SDK_VERSION=Fa;
|