@vkontakte/videoplayer-core 2.0.82 → 2.0.83-dev.65744ed.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +64 -6
- package/es2015.esm.js +64 -6
- package/es2018.cjs.js +64 -6
- package/es2018.esm.js +64 -6
- package/esnext.cjs.js +64 -6
- package/esnext.esm.js +64 -6
- package/evergreen.esm.js +64 -6
- package/index.d.ts +9 -0
- package/package.json +1 -1
package/esnext.cjs.js
CHANGED
|
@@ -1,8 +1,66 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.83-dev.65744ed.0
|
|
3
|
+
* Wed, 19 Apr 2023 17:05:19 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-83/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Ds=Object.create;var xt=Object.defineProperty;var _s=Object.getOwnPropertyDescriptor;var Cs=Object.getOwnPropertyNames;var Is=Object.getPrototypeOf,Ls=Object.prototype.hasOwnProperty;var xs=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Cs(e))!Ls.call(r,a)&&a!==t&&xt(r,a,{get:()=>e[a],enumerable:!(s=_s(e,a))||s.enumerable});return r};var Bt=(r,e,t)=>(t=r!=null?Ds(Is(r)):{},xs(e||!r||!r.__esModule?xt(t,"default",{value:r,enumerable:!0}):t,r));var i=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),Bs=require("lodash/debounce.js");const Os="2.0.82",Ms="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 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 Fs{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||Vs("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(Us),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 Us=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 Ye;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Ye||(Ye={}));var Ge=(r,e=0,t=Ye.OFFSET_P)=>{switch(t){case Ye.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Ye.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}},pt=(r,e)=>he[r].height>he[e].height,Hs=(r,e)=>he[r].height>=he[e].height,st=(r,e)=>he[r].height<he[e].height,qs=(r,e)=>he[r].height<=he[e].height,Ys=r=>r.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:st(e,t)?1:-1)[0],Gs=Object.keys(he).sort((r,e)=>st(r,e)?-1:1),Ve=({width:r,height:e})=>{const t=Math.min(r,e),s=Math.max(r,e);return Gs.find(a=>{const n=he[a];return n.width>=s&&n.height>=t})},js=r=>he[r].height,St=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 zs=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 Qs=5,Ws=5,Js=500,Ot=7e3;class Ks{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(zs(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(Js)).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)>Qs)&&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<Ws&&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=Ys(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=Ge(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(Ot).subscribe(()=>n(`timeout(${Ot})`)))});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 Mt{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 us extends Mt{constructor(){super(),this.listeners||Mt.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 cs=class{constructor(){Object.defineProperty(this,"signal",{value:new us,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&&(cs.prototype[Symbol.toStringTag]="AbortController",us.prototype[Symbol.toStringTag]="AbortSignal");function ds(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 Xs(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!ds({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 kt=ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ls=kt?Xs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,je=kt?ls.fetch:window.fetch;kt?ls.Request:window.Request;const Oe=kt?cs:window.AbortController,Ze=r=>r.range?r.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class it{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]=Ze(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(Ze),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 Oe,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 je(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($,it.suppressStreamErrors).catch(h))};m?.read().then($,it.suppressStreamErrors).catch(h)},it.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]=Ze(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]=Ze(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]=Ze(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 bt{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(bt.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;bt.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Zs=(r,e)=>t=>({create:s=>{const a=r(t).create(s);return new bt(a,e,s)}}),ei=(r,e)=>{const t=new it(e);return r.extend("SchemeLoaderFactory",function(){const{parent:s}=this,a=s.getLoader;return{getLoader:n=>{const o=a(n);return Zs(o,t)}}},!0),()=>t.destroy()};var ti=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)},si=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}},ze=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},ii=r=>r.extend("RequestModifier",()=>({modifyRequestURL:ze}),!0),ai=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},Fe=(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}),Ce=(r,e,t,s)=>me(e,()=>r.playbackRate,a=>{i.isNonNullable(a)&&(r.playbackRate=a)},{changed$:t,onError:s}),ri=r=>["__",r.language,r.label].join("|"),ni=(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:ri(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)&&ni(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 _t{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}}var hs=()=>{const{userAgent:r}=window.navigator;return!/chrome/i.test(r)&&/webkit|safari|khtml/i.test(r)};const Nt=3;class oi{_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<Nt&&(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||Nt))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 fs=(r,e,t=Nt)=>{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 ui=50,ci=r=>r.webkitAudioDecodedByteCount!=="undefined"?!!r.webkitAudioDecodedByteCount:r.mozHasAudio!=="undefined"?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(()=>fs(r.buffered,r.currentTime))),n=hs()?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(ui),i.map(()=>ci(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}},Ct=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let It=!1,Te={};const di=r=>{It=r},li=()=>{Te={}},hi=r=>{r(Te)},dt=(r,e)=>{It&&(Te.meta=Te.meta??{},Te.meta[r]=e)};class pe{name;constructor(e){this.name=e}next(e){if(!It)return;Te.series=Te.series??{};const t=Te.series[this.name]??[];t.push([Date.now(),e]),Te.series[this.name]=t}}const fi=new pe("best_bitrate"),pi=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class mi{last;history={};recordSelection(e){this.history[e.id]=i.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const nt=(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&&Ve(h),S=s.considerPlaybackRate&&i.isNonNullable(u)?u:1,p=r.filter(_=>!St(_.quality)).sort((_,q)=>pt(_.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)&&st(a.max,a.min)||i.isNonNullable(a.min)&&b&&pt(a.min,b)||i.isNonNullable(a.max)&&m&&st(a.max,m),$=S*pi(o??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),E=p.filter(_=>{const q=f?st(_.quality,f):!0,C=i.isNonNullable(t)&&isFinite(t)&&i.isNonNullable(_.bitrate)?t-n>=_.bitrate*$:!0,M=s.lazyQualitySwitch&&i.isNonNullable(s.minBufferToSwitchUp)&&d&&!St(d.quality)&&(o??0)<s.minBufferToSwitchUp&&pt(_.quality,d.quality),j=v||(i.isNullable(a.max)||qs(_.quality,a.max))&&(i.isNullable(a.min)||Hs(_.quality,a.min));return q&&C&&!M&&j})[0];E&&E.bitrate&&fi.next(E.bitrate);const y=E??p[Math.ceil((p.length-1)/2)]??r[0],D=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&&!D&&c.recordSelection(y),D&&c?.last){const _=c.last;return c?.recordSwitch(_),_}return c?.recordSwitch(y),y};var ae=r=>new URL(r).hostname;const Si=300,gt=(r,e=Si)=>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(Bs(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()}),bi=5e3,et={};var N;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(N||(N={}));const K=(r,e)=>new i.Observable(t=>{const s=a=>t.next(a);return r.on(e,s),()=>r.off(e,s)});class Vt{subscription=new i.Subscription;videoState=new G(N.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 _t;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"),bi);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(et.MediaPlayer=a.MediaPlayer,et.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){i.assertNonNullable(et.MediaPlayer,"dashjs not loaded"),i.assertNonNullable(et.Debug,"dashjs not loaded"),this.player=et.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?Ct(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=ei(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&&ai(this.player),ti(this.player),this.params.tuning.requestQuick&&ii(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(N.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(gt(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===N.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),D=Ve(E),_=E.bitrate/1e3,q={width:E.width,height:E.height},C=this.frameRatesByFrameHeight[E.height];if(D){const M={id:y,quality:D,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(N.STREAM_INITIALIZED),this.videoState.startTransitionTo(N.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=nt(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(()=>fs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(K(this.player,"playbackPlaying"),()=>{this.videoState.setState(N.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)}),a(K(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(N.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(N.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)}),a(K(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===N.READY&&this.videoState.setState(N.READY)}),a(this.isLive$,e.isLive$),a(gt(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}=si(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(Fe(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(Ce(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(N.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(N.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=Ge(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ye.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(N.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(N.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===N.DOWNLOADING_LIB||e===N.STREAM_INITIALIZED))switch(s?.to!==exports.PlaybackState.PAUSED&&a.state===P.Requested&&e!==N.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 N.STOPPED:break;case N.PLAYING:case N.PAUSED:case N.READY:this.stop();break;default:i.assertNever(e)}break}case exports.PlaybackState.READY:{switch(e){case N.STOPPED:this.prepare();break;case N.PLAYING:case N.PAUSED:case N.READY:break;default:i.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case N.PLAYING:break;case N.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 N.READY:this.play();break;case N.STOPPED:this.prepare();break;default:i.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case N.PLAYING:this.pause(),this.liveOffset.pause();break;case N.PAUSED:break;case N.READY:this.videoState.setState(N.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case N.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{}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var ot=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}},Ie=async r=>{const e=r.muted;try{await r.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(s){return r.muted=!1,console.warn(s),!1}}return!0};function se(){return i.now()}function ps(r){return se()-r}function Ft(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 gi(r,e,t){const s=(...a)=>{t.apply(null,a),r.removeEventListener(e,s)};r.addEventListener(e,s)}function mt(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=ps(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,D()};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),D=()=>{l=se(),o=new a,o.open("get",r);let O=0,J,fe=0;const Pe=()=>(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(Pe(),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(Pe(),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:D,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return j}const yi=100,Ei=2e3,Ti=500;let vi=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-Ti;if(t-e>Ei){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>yi&&(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 ki{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=mt(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 lt=1e4,ht=3,Ai=300,$i=2e3,Pi=6e4,wi=10,Ni=1,Ri=500;class Di{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 vi(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 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=()=>{gi(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 ki(ht,lt,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,D)=>{d&&d.abort(),d=mt(this.urlResolver.resolve(E,!1),y,D,()=>this._retryCallback()).withTimeout(lt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ht).withFinally(()=>{d=null}).send()},S=(E,y,D)=>{i.assertNonNullable(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),y,D,()=>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 D=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<D&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${E} drop=${_} jitter=${this.sourceJitter}`);let q=E-Ni;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 D=()=>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=D();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=D(),W=A?A.chunkIdx+1:0,X=W-y.fragIndex;if(!(V<=0)){if(!A||X<0||X-V>wi)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=mt(this.urlResolver.resolve(A,!0,this.lowLatency),V,W,()=>this._retryCallback()).withTimeout(lt).withRetryCount(ht).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 we=0;we<y.dur.length;++we)ie+=y.dur[we];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:D}=this.params;let _=v(e.jidxUrl),q,C,M,j,O=0,J,fe,Pe;const A=()=>{J&&(clearTimeout(J),J=void 0);const I=Math.max(Ri,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,We(I);const ee=_.nextChunk(M);if(ee){if(M&&ee.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?A():($(),this._initPlayerWith(e));return}we(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)D("Source buffer is updating; delaying appendBuffer"),ge(100);else{const le=se(),Ne=y.currentTime;!this.paused&&y.buffered.length>1&&fe===Ne&&le-Pe>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),fe!==Ne&&(fe=Ne,Pe=le);const Re=this._getBufferSizeSec();if(Re>30)D(`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(De){if(De.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),be=this.sourceBuffer.buffered.length,be!==0&&(Z=this.sourceBuffer.buffered.start(0),te=Ne,te-Z>4&&this.sourceBuffer.remove(Z,te-3)),ge(1e3);else throw De}}},X=()=>{C&&q&&(D([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(M)]),W(C,function(){C=null,V()}))},ie=I=>e.fragUrlTemplate.replace("%%id%%",I.chunkIdx),we=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())},We=I=>{h()&&(i.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(I),!1)))},ct=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?we(I):(M=I,V())}},E),e.cachedHeader?ct(e.cachedHeader):f(e.headerUrl,ct,()=>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&&ps(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=mt(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(lt).withRetryCount(ht).withRetryInterval(Ai,$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: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))},Pi))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var R;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(R||(R={}));const _i=[R.PAUSED,R.PLAYING,R.READY],Ci=[R.PAUSED,R.PLAYING,R.READY];class Ii{subscription=new i.Subscription;video;videoState=new G(R.STOPPED);dash;representations$=new i.ValueSubject([]);textTracksManager=new Se;maxSeekBackTime$=new i.ValueSubject(1/0);zeroTime$=new i.ValueSubject(void 0);liveOffset=new _t;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===R.READY&&this.videoState.setState(R.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(R.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===P.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(R.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(Fe(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(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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&js(a);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case R.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case R.MANIFEST_READY:case R.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case R.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case R.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.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Di({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:nt(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=-e,s=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(Ge(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: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=ot(a.name)??Ve(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===R.MANIFEST_READY&&this.videoState.setState(R.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!==R.STOPPED&&(this.videoState.startTransitionTo(R.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(R.STOPPED));return}if(!t){if(Ci.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&&_i.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case R.STOPPED:this.videoState.startTransitionTo(R.MANIFEST_READY),this.dash.attachSource(Ge(this.params.source.url));return;case R.MANIFEST_READY:this.videoState.startTransitionTo(R.READY),this.prepare();break;case R.READY:if(s===exports.PlaybackState.PAUSED)this.videoState.setState(R.PAUSED);else if(s===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(R.PLAYING);const o=a?.from;o&&o===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(R.PAUSED)})}return;case R.PLAYING:s===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(R.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case R.PAUSED:s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(R.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(R.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return i.assertNever(e)}}}}var ms=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}},Be=(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 Li=r=>{const e=document.createElement("a");return e.href=r,e.origin},xi=r=>{const e=document.createElement("a");return e.href=r,e.host};class Ss{_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(xi(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 yt{_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(yt._str2ua(m.substr(d))),d=m.length};let p=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(p=ze(p)),this._lastXhr=new Ss(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=yt._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 Bi{_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=ze(s)),new Ss(s,t,a=>{this.attachManifest(a,t,Li(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,D=F.getAttribute("lang")??void 0;y&&d.push({id:E,url:y,language:D})}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=$?Ct($):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 yt({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 Oi=[L.PAUSED,L.PLAYING];class Mi{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 oi(this.video),this.dash=new Bi({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(Fe(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(Ce(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),o(gt(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=Be(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=nt(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=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||!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}=ms(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.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return 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&&ot(s.name))??Ve(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(){Ie(this.video).then(e=>{e||(this.videoState.setState(L.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(L.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(a?.to!==exports.PlaybackState.PAUSED&&n.state===P.Requested&&Oi.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 Et;(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"})(Et||(Et={}));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 Qe;(function(r){r.MP4="mp4",r.WEBM="webm"})(Qe||(Qe={}));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 Vi=(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)},Fi=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ut=Fi?Vi:window.requestIdleCallback;let bs=!1;try{bs=hs()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class Ui{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;bs&&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)}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"&&t==="remove"||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 Ht=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};const gs=new TextDecoder("ascii"),ys=r=>{let e=0,t=r.getUint32(e);e+=4;const s=new DataView(r.buffer,r.byteOffset+e,4),a=gs.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}},Hi=r=>gs.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",qi=(r,e,t)=>{const s=ys(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},Yi=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=ys(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},Gi={validateData:Hi,parseInit:()=>null,getIndexRange:()=>{},parseSegments:qi,parseFeedableSegmentChunk:Yi};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 qt={[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}},Es=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=Tt(r,t),a=s in qt,n=a?qt[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=Tt(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}},Tt=(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 Tt(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)}},ut=(r,e)=>{let t=0;for(;t<r.byteLength;){const s=new DataView(r.buffer,r.byteOffset+t),a=Es(s);if(!e(a))return;a.type===k.Master&&ut(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},ji=r=>{if(r.getUint32(0)!==g.EBML)return!1;let e,t,s;const a=Es(r);return ut(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)},Ts=[g.Info,g.SeekHead,g.Tracks,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],zi=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],Qi=r=>{let e,t,s,a,n=!1,o=!1,u=!1,d,c;return ut(r,({tag:l,type:h,value:f,valueSize:S})=>{if(l===g.SeekID){const p=ve(f,h);c=Tt(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&&Ts.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}},Wi=r=>{if(i.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ji=(r,e)=>{let t=!1,s=!1;const a=u=>i.isNonNullable(u.time)&&i.isNonNullable(u.position),n=[];let o;return ut(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&&Ts.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}}})},Ki=r=>{let e=0,t=!1;try{ut(r,s=>s.tag===g.Cluster?s.tagSize<=r.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):zi.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},Xi={validateData:ji,parseInit:Qi,getIndexRange:Wi,parseSegments:Ji,parseFeedableSegmentChunk:Ki};class Yt{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 Oe;destroyAbortController=new Oe;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 Qe.MP4:this.containerParser=Gi;break;case Qe.WEBM:this.containerParser=Xi;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 Ui(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,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),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 Oe,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=Be(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)&&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&&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&&Be(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(){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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),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=Be(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(D=>{if(n.aborted)o();else if(D)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=Ut(()=>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=Ut(()=>{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 qe;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(qe||(qe={}));class Zi{throughputEstimator;requestQuic;lastConnectionType$=new i.ValueSubject(void 0);lastConnectionReused$=new i.ValueSubject(void 0);lastRequestFirstBytes$=new i.ValueSubject(void 0);abortAllController=new Oe;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}=ms(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=i.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ze(t));const s=yield je(t,{signal:this.abortAllController.signal}).catch(tt);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=i.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?qe.HEADER:qe.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 qe.HEADER:{c.append("Range",`bytes=${s.from}-${s.to}`);break}case qe.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=ze(d));let l=this.abortAllController.signal;if(o){const C=new Oe;if(this.subscription.add(i.merge(i.fromEvent(this.abortAllController.signal,"abort"),i.fromEvent(o,"abort")).subscribe(()=>{try{C.abort()}catch(M){tt(M)}})),this.abortAllController.signal.aborted||o.aborted)try{C.abort()}catch(M){tt(M)}l=C.signal}const h=i.now(),f=yield je(d,{priority:n,headers:c,signal:l}).catch(tt),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 D=!1;const _=C=>{D=!0,tt(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,_),D?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 tt=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},Gt=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},$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[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},ea=(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=Gt(c);else if(l){const p=Gt(l);i.isNonNullable(p)&&(d=p)}let h=0;const f=n.getAttribute("profiles")?.split(",")??[],S=f.includes(Et.WEBM_AS_IN_FFMPEG)||f.includes(Et.WEBM_AS_IN_SPEC)?Qe.WEBM:Qe.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 D=y.getAttribute("mimeType")??m,_=y.getAttribute("codecs")??b??"",q=y.getAttribute("contentType")??D?.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,Pe=J?Ct(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(),we=[...f,...$,...C];let We;const ct=y.querySelector("SegmentBase"),I=y.querySelector("SegmentTemplate")??E;if(ct){const Z=y.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[te,be]=Z.split("-").map(Le=>parseInt(Le,10)),ge={from:te,to:be},le=y.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ne,Re]=le?le.split("-").map(Le=>parseInt(Le,10)):[],De=le?{from:Ne,to:Re}:void 0;We={type:ce.BYTE_RANGE,url:ie,initRange:ge,indexRange:De}}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,Ne=$t(be,Z);if(!ge)throw new ReferenceError("No media attribute in SegmentTemplate");const Re=I.querySelectorAll("SegmentTimeline S")??[],De=[];if(Re.length){let Le=le,xe=0;for(const Je of Re){const Ue=parseInt(Je.getAttribute("d")??"",10)*1e3,Ke=parseInt(Je.getAttribute("r")??"",10)||0,Xe=parseInt(Je.getAttribute("t")??"",10)??void 0;for(let Lt=0;Lt<Ke+1;Lt++){const ws=$t(ge,{...Z,segmentNumber:Le.toString(10),segmentTime:Xe.toString(10)}),Ns=Xe?Xe/te:xe;xe+=Ue/te;const Rs=xe;Le++,De.push({time:{from:Ns,to:Rs},url:ws})}}}else if(i.isNonNullable(d)){const xe=parseInt(I.getAttribute("duration")??"",10)/te*1e3,Je=Math.ceil(d/xe);let Ue=0;for(let Ke=1;Ke<Je;Ke++){const Xe=$t(ge,{...Z,segmentNumber:Ke.toString(10),segmentTime:Ue.toString(10)});De.push({time:{from:Ue,to:Ue+xe},url:Xe}),Ue+=xe}}We={type:ce.TEMPLATE,baseUrl:ie,initUrl:Ne,segments:De}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!q||!D)continue;const ee={video:ue.VIDEO,audio:ue.AUDIO,text:ue.TEXT}[q];ee&&a[ee].push({id:W,kind:ee,segmentReference:We,profiles:we,duration:d,bitrate:O,mime:D,codecs:_,width:M,height:j,fps:Pe,quality:fe})}}return{duration:d,container:S,representations:a}},ta=["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 sa=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 Oe;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Zi({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=ea(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 Yt(ue.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],i.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 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(...ta.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=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 ia=({id:r,width:e,height:t,bitrate:s,fps:a,quality:n})=>{const o=(n?ot(n):void 0)??Ve({width:e,height:t});return o&&{id:r,quality:o,bitrate:s,size:{width:e,height:t},fps:a}},aa=({id:r,bitrate:e})=>({id:r,bitrate:e}),ra=(r,e,t)=>{const s=e.indexOf(t);return r.at(Math.round(r.length*s/e.length))??r.at(-1)};class na{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 mi;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 sa({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(Fe(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(Ce(this.video,t.playbackRate,s.playbackRateState$,a)),n(gt(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=aa(p);m&&this.audioTracks.push({track:m,representation:p})}for(const p of f){const m=ia(p);if(m){this.videoTracks.push({track:m,representation:p});const b=!this.params.tuning.isAudioDisabled&&ra(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=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,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),c=nt(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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const oa=5e3,ye={};var x;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(x||(x={}));const ft=(r,e)=>new i.Observable(t=>{const s=(a,n)=>t.next(n);return r.on(e,s),()=>r.off(e,s)});class ua{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.video.remove(),this.params.output.element$.next(void 0)}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"),oa);import("hls.js/dist/hls.min.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(Fe(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(Ce(this.video,e.playbackRate,a.playbackRateState$,s)),this.subscription.add(ft(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(ft(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=ot(h.attrs.QUALITY??"")??Ve({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(ft(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=ft(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 Ie(this.video)||(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.setAttribute("src",""),this.video.load(),this.videoState.setState(x.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const jt="X-Playback-Duration";var zt=async r=>{const e=await je(r,{method:"HEAD"});return e.headers.has(jt)?parseInt(e.headers.get(jt),10):void 0};const ca=r=>{let e=null;if(r.QUALITY&&(e=ot(r.QUALITY)),!e&&r.RESOLUTION){const[t,s]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Ve({width:t,height:s})}return e??null},vs=async(r,e=r)=>{const a=(await(await je(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=ca(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 da{subscription=new i.Subscription;videoState=new G(U.STOPPED);video;params;textTracksManager=new Se;manifests$=new i.ValueSubject([]);maxSeekBackTime$;liveOffset=new _t;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]),vs(Ge(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(Ce(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.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(i.isNullable(e))return;const t=Ge(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),zt(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{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=>{i.isNullable(d)||this.maxSeekBackTime$.next(d)})}})}catch{}}})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const 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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(U.STOPPED),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 la{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)),vs(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(Fe(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(Ce(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.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();i.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))})}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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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 ha{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(Fe(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(Ce(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.video.remove(),this.params.output.element$.next(void 0)}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=ze(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))})}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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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 Qt=["stun:videostun.mycdn.me:80"],fa=1e3,pa=3,Pt=()=>null;class ma{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Pt;externalStopCallback=Pt;externalErrorCallback=Pt;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: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),fa)}normalizeOptions(e={}){const t={stunServerList:Qt,maxRetryNumber:pa,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 Sa{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 ma(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState: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(){Ie(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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 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 ba=()=>{const r=window.navigator;return r.userAgentData?r.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const ks=ba(),vt=document.createElement("video"),Ee={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(vt.canPlayType?.("application/x-mpegurl")||vt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},ne={mp4:Boolean(vt.canPlayType?.("video/mp4")),webm:Boolean(vt.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"'))},He=(_e.h264||_e.h265)&&_e.aac,At=Ee.hls&&ne.mp4,ga=Boolean(window.WebSocket),ya=()=>Object.keys(_e).filter(r=>_e[r]),Ea=(r,e=!1)=>r.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Ee.mse&&ne.mp4&&He;case exports.VideoFormat.DASH_SEP:return Ee.mse&&ne.mp4&&He;case exports.VideoFormat.DASH_WEBM:return Ee.mse&&ne.webm&&_e.vp9&&_e.opus;case exports.VideoFormat.DASH_LIVE:return Ee.mse&&ne.mp4&&He;case exports.VideoFormat.DASH_LIVE_CMAF:return Ee.mse&&ne.mp4&&He&&ne.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Ee.mse&&ne.mp4&&He;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return At||e&&Ee.mse&&ne.mp4&&He;case exports.VideoFormat.MPEG:return ne.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ee.webrtc&&ga&&_e.h264&&(ne.mp4||ne.webm);default:return i.assertNever(t)}}),Ta=()=>ks?[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]:At?[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],va=()=>ks?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:At?[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 ka=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 Kt={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Aa={cacheDuration:12e4},$a={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Pa={maxPausedTime:3e4},Xt={maxPausedTime:3e4};class wa{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=Ea([...va(),...Ta()],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 Wt(a);const n=[...Jt(!0),...Jt(!1)];this.chromecastFormatsIterator=new Wt(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 Mi({...o,source:u,config:Aa})}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 Vt({...o,source:u,format:e,config:Xt}):new na({...o,source:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new Vt({...o,source:u,format:e,config:Xt})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),At||!this.params.tuning.useHlsJs?new la({...o,source:u}):new ua({...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 da({...o,source:u,config:Pa})}case exports.VideoFormat.MPEG:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new ha({...o,source:u})}case exports.VideoFormat.DASH_LIVE:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new Ii({...o,source:u,config:$a})}case exports.VideoFormat.WEB_RTC_LIVE:{const u=this.applyFailoverHost(t[e]);return i.assertNonNullable(u),new Sa({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 Ks({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$,ka({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Kt.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<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}}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 As=new Map;let Me=de.RUNTIME;const wt=`vk-videoplayer-dummy-key-${Math.random()}`,Na=()=>{try{localStorage.setItem(wt,"test"),localStorage.removeItem(wt),Me=de.LOCAL_STORAGE}catch(r){if(r instanceof DOMException||r instanceof TypeError)try{sessionStorage.getItem(wt),Me=de.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Me=de.RUNTIME;else throw e}else throw r}};Na();const Ra=r=>{switch(Me){case de.LOCAL_STORAGE:return localStorage.getItem(r)??void 0;case de.SESSION_STORAGE:return sessionStorage.getItem(r)??void 0;case de.RUNTIME:return As.get(r);default:i.assertNever(Me)}},Zt=(r,e)=>{switch(Me){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 As.set(r,e);default:i.assertNever(Me)}},Dt=(r,e,t)=>t*e+(1-t)*r,$s=(r,e)=>r.reduce((t,s)=>t+s,0)/e,Da=(r,e,t,s)=>{let a=0,n=t;const o=$s(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 Ps{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 _a extends Ps{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 Ca extends Ps{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=$s(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);const s=Da(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class es{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new _a({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Ca({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const Ia=5e3,ts="one_video_throughput",ss="one_video_rtt",at=window.navigator.connection,is=()=>{const r=at?.downlink;if(i.isNonNullable(r)&&r!==10)return r*1e3},as=()=>{const r=at?.rtt;if(i.isNonNullable(r)&&r!==3e3)return r},rs=(r,e,t)=>{const s=t*8,a=s/r;return s/(a+e)};class rt{throughput;rtt;subscription=new i.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=rt.load(ts)||(e.useBrowserEstimation?is():void 0)||Ia,s=rt.load(ss)??(e.useBrowserEstimation?as():void 0)??0;if(this.throughput$=new i.ValueSubject(t),this.rtt$=new i.ValueSubject(s),this.rttAdjustedThroughput$=new i.ValueSubject(rs(t,s,e.rttPenaltyRequestSize)),this.throughput=es.getSmoothedValue(t,-1,e),this.rtt=es.getSmoothedValue(s,1,e),e.useBrowserEstimation){const a=()=>{const o=is();o&&this.throughput.next(o);const u=as();i.isNonNullable(u)&&this.rtt.next(u)};at&&"onchange"in at&&this.subscription.add(i.fromEvent(at,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Zt(ts,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Zt(ss,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})=>rs(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(rt.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=Ra(e);if(i.isNonNullable(t))return parseInt(t,10)??void 0}}const ns={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}},La=r=>{const e={};for(const t of Object.keys(ns)){const s=ns[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 xa=({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))),Ba=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 os=({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 Oa{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:hi};constructor(e={}){if(this.initLogs(),this.tuning=La(e),this.chromecastInitializer=new Fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new rt(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=Ba(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new wa({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)=>St(c)?1:St(l)?-1:pt(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(xa({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(os({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(os({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=nt(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),li(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>di(t)),this.providerContainer.current$.subscribe(({type:t})=>dt("provider",t)),e.duration$.subscribe(t=>dt("duration",t)),e.availableVideoTracks$.pipe(i.filter(t=>!!t.length),i.once()).subscribe(t=>dt("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)),dt("codecs",ya())}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=>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 Ma=`${Ms}@${Os}`;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=Oa;exports.SDK_VERSION=Ma;
|
|
6
|
+
"use strict";var Vs=Object.create;var Yt=Object.defineProperty;var Os=Object.getOwnPropertyDescriptor;var Fs=Object.getOwnPropertyNames;var Us=Object.getPrototypeOf,Hs=Object.prototype.hasOwnProperty;var Ys=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fs(e))!Hs.call(r,i)&&i!==t&&Yt(r,i,{get:()=>e[i],enumerable:!(s=Os(e,i))||s.enumerable});return r};var qt=(r,e,t)=>(t=r!=null?Vs(Us(r)):{},Ys(e||!r||!r.__esModule?Yt(t,"default",{value:r,enumerable:!0}):t,r));var a=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),qs=require("lodash/debounce.js");const js="2.0.83-dev.65744ed.0",Gs="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 w;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(w||(w={}));var zs=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 Qs{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||zs("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(Ws),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 c=s.getCurrentSession();a.assertNonNullable(c);const d=c.getCastDevice(),u=c.getMediaSession()?.media.contentId;(a.isNullable(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,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 Ws=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 ze;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ze||(ze={}));var Qe=(r,e=0,t=ze.OFFSET_P)=>{switch(t){case ze.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ze.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 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}},Tt=(r,e)=>he[r].height>he[e].height,Js=(r,e)=>he[r].height>=he[e].height,ct=(r,e)=>he[r].height<he[e].height,Xs=(r,e)=>he[r].height<=he[e].height,Ks=r=>r.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:ct(e,t)?1:-1)[0],Zs=Object.keys(he).sort((r,e)=>ct(r,e)?-1:1),Ue=({width:r,height:e})=>{const t=Math.min(r,e),s=Math.max(r,e);return Zs.find(i=>{const n=he[i];return n.width>=s&&n.height>=t})},ei=r=>he[r].height,vt=r=>r===exports.VideoQuality.INVARIANT;class j{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 ti=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 $;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})($||($={}));const si=5,ii=5,ai=500,jt=7e3;class ri{subscription=new a.Subscription;loadMediaTimeoutSubscription=new a.Subscription;videoState=new j($.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(ti(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(ai)).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 c=o.value;this.params.output.position$.next(c),(this.params.desiredState.seekState.getState().state===w.Applying||Math.abs(c-n)>si)&&i.next(c),n=c})),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,c=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(c!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<ii&&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($.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState($.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:w.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===$.PAUSED||e===$.PLAYING)&&(this.videoState.setState($.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===$.PLAYING||e===$.PAUSED)&&(this.videoState.setState($.PLAYING),T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===$.READY&&this.videoState.setState($.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&T(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==$.STOPPED&&this.videoState.setState($.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),s={volume:e.volume??t.volume,muted:e.muted??t.muted};(s.volume!==t.volume||s.muted!==s.muted)&&this.params.output.volume$.next(s)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let s,i,n;switch(e){case exports.VideoFormat.MPEG:{const u=t[e];a.assertNonNullable(u);const l=Ks(Object.keys(u));a.assertNonNullable(l);const h=u[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 u=t[e];a.assertNonNullable(u),s=u.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 u=t[e];a.assertNonNullable(u),s=u.url,i="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=t[e];a.assertNonNullable(u),s=u.url,i="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=t[e];a.assertNonNullable(u),s=Qe(u.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 u="Unsupported format for Chromecast",l=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:u,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:c,subtitle:d}=this.params.meta;return a.isNonNullable(c)&&(o.metadata.title=c),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===w.Applying||s.state===w.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(jt).subscribe(()=>n(`timeout(${jt})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===w.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!==$.STOPPED&&(this.videoState.startTransitionTo($.STOPPED),this.stop());return}if(!t){if(i?.to!==exports.PlaybackState.PAUSED&&n.state===w.Requested&&e!==$.STOPPED){this.seek(n.position/1e3);return}switch(s){case exports.PlaybackState.READY:{switch(e){case $.PLAYING:case $.PAUSED:case $.READY:break;case $.STOPPED:this.videoState.startTransitionTo($.READY),this.prepare();break;default:a.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case $.PLAYING:break;case $.PAUSED:this.videoState.startTransitionTo($.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case $.READY:this.videoState.startTransitionTo($.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case $.STOPPED:this.videoState.startTransitionTo($.READY),this.prepare();break;default:a.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case $.PLAYING:this.videoState.startTransitionTo($.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case $.PAUSED:break;case $.READY:this.videoState.startTransitionTo($.PAUSED),this.videoState.setState($.PAUSED);break;case $.STOPPED:this.videoState.startTransitionTo($.READY),this.prepare();break;default:a.assertNever(e)}break}default:a.assertNever(s)}}}}class Gt{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(c){Promise.resolve().then(()=>{throw c})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class bs extends Gt{constructor(){super(),this.listeners||Gt.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 gs=class{constructor(){Object.defineProperty(this,"signal",{value:new bs,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&&(gs.prototype[Symbol.toStringTag]="AbortController",bs.prototype[Symbol.toStringTag]="AbortSignal");function ys(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 ni(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=r;if(!ys({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(u,l){let h;l&&l.signal&&(h=l.signal,delete l.signal);const p=new t(u,l);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const l=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.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 p=new Promise((S,f)=>{l.addEventListener("abort",()=>f(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,o(d,u)])}return o(d,u)},Request:n}}const _t=ys({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ts=_t?ni({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,We=_t?Ts.fetch:window.fetch;_t?Ts.Request:window.Request;const Oe=_t?gs:window.AbortController,at=r=>r.range?r.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ut{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]=at(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(at),i=s[0][0];let n=s[0][1];for(let p=1;p<s.length&&n<this.params.minDataSize;p++){const S=s[p][1];S-i<=2*this.params.minDataSize&&(n=Math.max(n,S))}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 c=o.toString(),d=new Oe,u=d.signal,l={url:e,from:i,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(l));const h=p=>{throw this.params.onError?.({id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:p}),p};return We(c,{signal:u}).then(p=>{if(l.response=p,!p.ok||!p.body){this.onBigRequestError(l);return}const[S,f]=p.body.tee();this.params.onDownloadStream?.(f);const m=S.getReader(),g=parseInt(p.headers.get("Content-Length")??"",10)||n-i+1;l.data=new ArrayBuffer(g);const k=new Uint8Array(l.data),P=async({done:H,value:E})=>{H?this.onBigRequestProgress(l):E&&(k.set(E,l.loaded),l.loaded+=E.byteLength,this.onBigRequestProgress(l),await m?.read().then(P,ut.suppressStreamErrors).catch(h))};m?.read().then(P,ut.suppressStreamErrors).catch(h)},ut.suppressAbort).catch(p=>this.onBigRequestError(l,p)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:n,response:o}){if(!this.activeRequests.has(e)||!n)return;const c=this.dashJsRequestQueue.get(e)??[];for(const d of c){const{request:u}=d,[l,h]=at(u),p=l>=t&&h<=t+i,S=t>=l&&t+i<h,f=n.slice(l-t,Math.min(h-t+1,i));if((p||S)&&(u.requestStartDate=u.requestStartDate??new Date,u.firstByteDate=u.firstByteDate??new Date,u.bytesLoaded=f.byteLength,u.bytesTotal=s-t),p){u.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(g=>g!==d)),d.success?.(f,"",e);const m=o?Array.from(o.headers.entries()).map(([g,k])=>`${g}: ${k}`).join(`\r
|
|
7
|
+
`):"";this.dashMetrics?.addHttpRequest(u,e,o?.status??200,m,[])}else S&&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[c,d]=at(o.request);(c>=t&&c<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,c]=at(n.request);(o>=t&&o<s||c>t&&c<=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 kt{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(kt.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;kt.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const oi=(r,e)=>t=>({create:s=>{const i=r(t).create(s);return new kt(i,e,s)}}),ci=(r,e)=>{const t=new ut(e);return r.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:n=>{const o=i(n);return oi(o,t)}}},!0),()=>t.destroy()};var ui=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)},di=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 c=()=>{n=Date.now(),o=!1},d=l=>{const h=Object.fromEntries(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(f=>f.split(": ")));if("x-playback-duration"in h||"x-playback-duration-millis"in h){const f=parseInt(l.getResponseHeader("X-Playback-Duration")??"",10),g=parseInt(l.getResponseHeader("X-Playback-Duration-Millis")??"",10)??f*1e3??NaN;a.isNonNullable(g)&&!isNaN(g)&&e.next(g)}const p=h["x-delivery-type"]??exports.HttpConnectionType.HTTP1,S={1:!0,0:!1}[h["x-reused"]]??void 0;s.next(p),i.next(S)},u=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(p){if(p.request.type==="MPD"){const S=p.onload,f=p.progress;p.onload=function(...m){return d(this),S(...m)},p.progress=function(...m){return u(this),f(...m)},c()}return h(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:i,connectionType$:s}},Je=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},li=r=>r.extend("RequestModifier",()=>({modifyRequestURL:Je}),!0),hi=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(c=>parseInt(c,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 Se=(r,e,t,{equal:s=(o,c)=>o===c,changed$:i,onError:n}={})=>{const o=r.getState(),c=e(),d=a.isNullable(i),u=new a.Subscription;return i&&u.add(i.subscribe(l=>{const h=r.getState();s(l,h)&&r.setState(l)},n)),s(c,o)||(t(o),d&&r.setState(o)),u.add(r.stateChangeStarted$.subscribe(l=>{t(l.to),d&&r.setState(l.to)},n)),u},He=(r,e,t)=>Se(e,()=>r.loop,s=>{a.isNonNullable(s)&&(r.loop=s)},{onError:t}),Ae=(r,e,t,s)=>Se(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}),Ie=(r,e,t,s)=>Se(e,()=>r.playbackRate,i=>{a.isNonNullable(i)&&(r.playbackRate=i)},{changed$:t,onError:s}),pi=r=>["__",r.language,r.label].join("|"),fi=(r,e)=>{if(r.id===e)return!0;const[t,s,i]=e.split("|");return r.language===s&&r.label===i};class be{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(Se(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:c},d)=>c===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:i})),this.subscription.add(Se(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(Se(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(be.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=e.id!==""?e.id:pi(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)&&fi(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 Pe=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 Ot{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}}var Es=()=>{const{userAgent:r}=window.navigator;return!/chrome/i.test(r)&&/webkit|safari|khtml/i.test(r)};const Bt=3;class mi{_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<Bt&&(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||Bt))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,c=n>=e&&n<t;o&&c||(o?s(t,n):c?s(i,e):i<e&&n>t?(s(t,n),s(i,e)):s(i,n))})}destroy(){this._buffer=[]}}var vs=(r,e,t=Bt)=>{let s=0,i=0;for(let n=0;n<r.length;n++){const o=r.start(n),c=r.end(n);if(o<=e&&e<=c){if(s=o,i=c,!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 Si=50,bi=r=>r.webkitAudioDecodedByteCount!=="undefined"?!!r.webkitAudioDecodedByteCount:r.mozHasAudio!=="undefined"?r.mozHasAudio:r.audioTracks?!!r.audioTracks.length:!0,we=r=>{const e=f=>a.fromEvent(r,f).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=a.merge(...t.map(f=>a.fromEvent(r,f))).pipe(a.map(f=>f.type==="ended"?r.readyState<2:r.readyState<3),a.filterChanged()),i=a.merge(a.fromEvent(r,"progress"),a.fromEvent(r,"timeupdate")).pipe(a.map(()=>vs(r.buffered,r.currentTime))),n=Es()?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(Si),a.map(()=>bi(r))),c=a.fromEvent(r,"volumechange").pipe(a.map(()=>({muted:r.muted,volume:r.volume}))),d=a.fromEvent(r,"ratechange").pipe(a.map(()=>r.playbackRate)),u=a.fromEvent(r,"error").pipe(a.filter(()=>Boolean(r.error||r.played.length)),a.map(()=>{const f=r.error;return{id:f?`MediaError#${f.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:f?f.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,p=.3;let S;return l.subscribe(f=>{r.loop&&a.isNonNullable(S)&&a.isNonNullable(f)&&S>=r.duration-p&&f<=p&&h.next(S),S=f}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,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$:c,isAudioAvailable$:o,playbackRateState$:d}},Ft=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let Ut=!1,ke={};const gi=r=>{Ut=r},yi=()=>{ke={}},Ti=r=>{r(ke)},St=(r,e)=>{Ut&&(ke.meta=ke.meta??{},ke.meta[r]=e)};class fe{name;constructor(e){this.name=e}next(e){if(!Ut)return;ke.series=ke.series??{};const t=ke.series[this.name]??[];t.push([Date.now(),e]),ke.series[this.name]=t}}const Ei=new fe("best_bitrate"),vi=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class ki{last;history={};recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ht=(r,{container:e,throughput:t,tuning:s,limits:i,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:d,history:u})=>{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},p=h&&Ue(h),S=s.considerPlaybackRate&&a.isNonNullable(c)?c:1,f=r.filter(C=>!vt(C.quality)).sort((C,Y)=>Tt(C.quality,Y.quality)?-1:1),m=f.at(-1)?.quality,g=f.at(0)?.quality,k=a.isNullable(i)||a.isNonNullable(i.min)&&a.isNonNullable(i.max)&&ct(i.max,i.min)||a.isNonNullable(i.min)&&g&&Tt(i.min,g)||a.isNonNullable(i.max)&&m&&ct(i.max,m),P=S*vi(o??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),E=f.filter(C=>{const Y=p?ct(C.quality,p):!0,N=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(C.bitrate)?t-n>=C.bitrate*P:!0,V=s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!vt(d.quality)&&(o??0)<s.minBufferToSwitchUp&&Tt(C.quality,d.quality),G=k||(a.isNullable(i.max)||Xs(C.quality,i.max))&&(a.isNullable(i.min)||Js(C.quality,i.min));return Y&&N&&!V&&G})[0];E&&E.bitrate&&Ei.next(E.bitrate);const y=E??f[Math.ceil((f.length-1)/2)]??r[0],_=y&&u&&u.history[y.id]&&a.now()-u.history[y.id]<=s.trackCooldown&&(!u.last||y.id!==u.last.id);if(y?.id&&u&&!_&&u.recordSelection(y),_&&u?.last){const C=u.last;return u?.recordSwitch(C),C}return u?.recordSwitch(y),y};var ae=r=>new URL(r).hostname;const Ai=300,At=(r,e=Ai)=>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(qs(o=>{const c=o[0];if(!c)return;let d,u;c.contentBoxSize&&c.contentBoxSize[0]?(u=c.contentBoxSize[0].blockSize,d=c.contentBoxSize[0].inlineSize):c.contentRect&&(d=c.contentRect.width,u=c.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(r),()=>n.disconnect()}),Pi=5e3,rt={};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 X=(r,e)=>new a.Observable(t=>{const s=i=>t.next(i);return r.on(e,s),()=>r.off(e,s)});class zt{subscription=new a.Subscription;videoState=new j(R.DOWNLOADING_LIB);video;player;params;textTracksManager=new be;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 Ot;destroyBigRequest;constructor(e){this.video=Pe(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"),Pi);import("dashjs/dist/dash.mediaplayer.min.js").then(i=>{e||(rt.MediaPlayer=i.MediaPlayer,rt.Debug=i.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(rt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(rt.Debug,"dashjs not loaded"),this.player=rt.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?Ft(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=ci(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&&hi(this.player),ui(this.player),this.params.tuning.requestQuick&&li(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(R.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},i=(m,g)=>this.subscription.add(m.subscribe(g,s));i(At(this.video),this.elementSize$),i(X(this.player,"error").pipe(a.map(m=>{const g=typeof m.error=="object"?m.error.code:m.error,k=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${g}`,message:k}})),e.error$),i(X(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=X(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===m)?.track));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:m})=>m===R.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Se(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===m)?.track?.id},m=>{if(a.isNullable(m))return;const g=this.videoTracks.find(({track:k})=>k.id===m)?.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:n.pipe(a.map(m=>m?.id)),onError:s}))},s)),this.subscription.add(Se(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:s})),i(X(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),i(X(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:g}})=>{const k=this.player.getDashMetrics(),P=k.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),H=k.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??exports.HttpConnectionType.HTTP1,E={1:!0,0:!1}[P]??void 0;this.params.output.httpConnectionType$.next(H),this.params.output.httpConnectionReused$.next(E),e.hostname$.next(ae(g))}),i(X(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:g,availableFrom:k}}})=>{this.isLive$.next(g),this.availableFrom$.next(k.getTime()),g||e.duration$.next(m),this.videoTracks=[];const P=this.player.getQualityFor("video");let H;for(const E of this.player.getBitrateInfoListFor("video")){const y=E.qualityIndex.toString(10),_=Ue(E),C=E.bitrate/1e3,Y={width:E.width,height:E.height},N=this.frameRatesByFrameHeight[E.height];if(_){const V={id:y,quality:_,bitrate:C,size:Y,fps:N};this.videoTracks.push({track:V,bitrateInfo:E}),E.qualityIndex===P&&(H=V)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),H&&e.currentVideoTrack$.next(H),this.videoState.setState(R.STREAM_INITIALIZED),this.videoState.startTransitionTo(R.READY)}),i(X(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const g=m.requestEndDate.getTime()-m.firstByteDate.getTime(),k=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(k,g)}),i(a.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(),g=ht(this.videoTracks.map(({track:P})=>P),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),k=this.videoTracks.find(({track:P})=>P===g);k?.bitrateInfo&&this.player.setQualityFor("video",k?.bitrateInfo.qualityIndex,!1)}),i(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=X(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m??0));i(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:g})=>this.params.output.liveTime$.next(m+g*1e3)),i(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),i(X(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),i(X(this.player,"playbackEnded"),e.endedEvent$),i(X(this.player,"playbackProgress").pipe(a.map(()=>vs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),i(X(this.player,"playbackPlaying"),()=>{this.videoState.setState(R.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)}),i(X(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(X(this.player,"playbackPaused"),()=>{this.videoState.setState(R.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)}),i(X(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===R.READY&&this.videoState.setState(R.READY)}),i(this.isLive$,e.isLive$),i(At(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const c=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));i(c,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:l,connectionReused$:h}=di(this.player);i(l,this.params.output.httpConnectionType$),i(h,this.params.output.httpConnectionReused$),i(d,this.maxSeekBackTime$),i(u.pipe(a.once()),e.firstBytesEvent$),i(X(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&i(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:g})=>{const k=!m&&g;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:k}}})}),i(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(X(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(X(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(He(this.video,t.isLooped,s));const{volumeState$:p,looped$:S,playbackRateState$:f}=we(this.video);this.subscription.add(Ae(this.video,t.volume,p,s)),this.subscription.add(p.subscribe(e.volume$,s)),this.subscription.add(S.subscribe(e.loopedEvent$)),this.subscription.add(Ie(this.video,t.playbackRate,f,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(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=Qe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ze.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===w.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{}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var pt=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}},xe=async r=>{const e=r.muted;try{await r.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(s){return r.muted=!1,console.warn(s),!1}}return!0};function se(){return a.now()}function ks(r){return se()-r}function Qt(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,c,d=!1)=>{i(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),c&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function wi(r,e,t){const s=(...i)=>{t.apply(null,i),r.removeEventListener(e,s)};r.addEventListener(e,s)}function Et(r,e,t,s){const i=window.XMLHttpRequest;let n,o,c,d=!1,u=0,l,h,p=!1,S="arraybuffer",f=7e3,m=2e3,g=()=>{if(d)return;a.assertNonNullable(l);const M=ks(l);let J;if(M<m){J=m-M,setTimeout(g,J);return}m*=2,m>f&&(m=f),o&&o.abort(),o=new i,_()};const k=M=>(n=M,G),P=M=>(h=M,G),H=()=>(S="json",G),E=()=>{if(!d){if(--u>=0){g(),s&&s();return}d=!0,h&&h(),t&&t()}},y=M=>(p=M,G),_=()=>{l=se(),o=new i,o.open("get",r);let M=0,J,pe=0;const $e=()=>(a.assertNonNullable(l),Math.max(l,Math.max(J||0,pe||0)));if(n&&o.addEventListener("progress",A=>{const O=se();n.updateChunk&&A.loaded>M&&(n.updateChunk($e(),A.loaded-M),M=A.loaded,J=O)}),c&&(o.timeout=c,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const A=o.status;if(A>=200&&A<300){if(o.response.byteLength&&n){const O=o.response.byteLength-M;O&&n.updateChunk&&n.updateChunk($e(),O)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),p){const A=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(pe=se(),o.removeEventListener("readystatechange",A))};o.addEventListener("readystatechange",A)}return o.responseType=S,o.send(),G},G={withBitrateReporting:k,withParallel:y,withJSONResponse:H,withRetryCount:M=>(u=M,G),withRetryInterval:(M,J)=>(a.isNonNullable(M)&&(m=M),a.isNonNullable(J)&&(f=J),G),withTimeout:M=>(c=M,G),withFinally:P,send:_,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return G}const $i=100,Ri=2e3,Di=500;let _i=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-Di;if(t-e>Ri){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,c=n.end-n.start;s+=o;const d=n.bytes*o/c;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>$i&&(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 Ci{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()},c=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Et(t,n,()=>i("error"),c),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 c=this.pendingQueue.indexOf(e);c!==-1&&this.pendingQueue.splice(c,1),this.logger(`Request not prefetched, starting new request, url=${e}${c===-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 bt=1e4,gt=3,Ni=300,Ii=2e3,xi=6e4,Li=10,Bi=1,Mi=500;class Vi{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 _i(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Qt(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=Qt(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 c=0;c<this.manifest.length;++c)n=this.manifest[c],!(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=()=>{wi(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 Ci(gt,bt,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,c=null,d=null,u=null,l=!1;const h=()=>{const E=n&&(!l||l===this.rep);return E||t("Not running!"),E},p=(E,y,_)=>{d&&d.abort(),d=Et(this.urlResolver.resolve(E,!1),y,_,()=>this._retryCallback()).withTimeout(bt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(gt).withFinally(()=>{d=null}).send()},S=(E,y,_)=>{a.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),y,_,()=>this._retryCallback()).withFinally(()=>{c=null}).send()},f=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}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}const _=se()-1e4;let C=0;for(let N=0;N<this.bufferStates.length;N++){const V=this.bufferStates[N];E=Math.min(E,V.buf),V.ts<_&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${E} drop=${C} jitter=${this.sourceJitter}`);let Y=E-Bi;this.sourceJitter>=0?Y-=this.sourceJitter/2:this.sourceJitter-=1,Y>3?f(1.15):Y>1?f(1.1):Y>.3?f(1.05):f(1)}},k=E=>{let y;const _=()=>y&&y.start?y.start.length:0,C=A=>y.start[A]/1e3,Y=A=>y.dur[A]/1e3,N=A=>y.fragIndex+A,V=(A,O)=>({chunkIdx:N(A),startTS:C(A),dur:Y(A),discontinuity:O}),G=()=>{let A=0;if(y&&y.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=O;this.sourceJitter>1&&(K+=this.sourceJitter-1);let ie=y.dur.length-1;for(;ie>=0&&(K-=y.dur[ie],!(K<=0));--ie);A=Math.min(ie,y.dur.length-1-W),A=Math.max(A,0)}return V(A,!0)},M=A=>{const O=_();if(!(O<=0)){if(a.isNonNullable(A)){for(let W=0;W<O;W++)if(C(W)>A)return V(W)}return G()}},J=A=>{const O=_(),W=A?A.chunkIdx+1:0,K=W-y.fragIndex;if(!(O<=0)){if(!A||K<0||K-O>Li)return t(`Resync: offset=${K} bChunks=${O} chunk=`+JSON.stringify(A)),G();if(!(K>=O))return V(W-y.fragIndex,!1)}},pe=(A,O,W)=>{u&&u.abort(),u=Et(this.urlResolver.resolve(A,!0,this.lowLatency),O,W,()=>this._retryCallback()).withTimeout(bt).withRetryCount(gt).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,O)=>{pe(E,W=>{if(!h())return;y=W;const K=Boolean(y.lowLatency);K!==this.lowLatency&&m(K);let ie=0;for(let Re=0;Re<y.dur.length;++Re)ie+=y.dur[Re];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,A(M(O))},()=>this._handleNetworkError())},nextChunk:J}},P=()=>{n=!1,c&&c.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:y,logger:_}=this.params;let C=k(e.jidxUrl),Y,N,V,G,M=0,J,pe,$e;const A=()=>{J&&(clearTimeout(J),J=void 0);const I=Math.max(Mi,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ee=M+I,Z=se(),te=Math.min(1e4,ee-Z);M=Z;const ye=()=>{u||h()&&C.seek(()=>{h()&&(M=se(),O(),A())})};te>0?J=window.setTimeout(()=>{this.paused?A():ye()},te):ye()},O=()=>{let I;for(;I=C.nextChunk(G);)G=I,et(I);const ee=C.nextChunk(V);if(ee){if(V&&ee.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?A():(P(),this._initPlayerWith(e));return}Re(ee)}else A()},W=(I,ee)=>{if(!h()||!this.sourceBuffer)return;let Z,te,ye;const Te=le=>{window.setTimeout(()=>{h()&&W(I,ee)},le)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),Te(100);else{const le=se(),De=y.currentTime;!this.paused&&y.buffered.length>1&&pe===De&&le-$e>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),pe!==De&&(pe=De,$e=le);const _e=this._getBufferSizeSec();if(_e>30)_(`Buffered ${_e} seconds; delaying appendBuffer`),Te(2e3);else try{this.sourceBuffer.appendBuffer(I),this.videoPlayStarted?(this.bufferStates.push({ts:le,buf:_e}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ee&&ee()}catch(Ce){if(Ce.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),ye=this.sourceBuffer.buffered.length,ye!==0&&(Z=this.sourceBuffer.buffered.start(0),te=De,te-Z>4&&this.sourceBuffer.remove(Z,te-3)),Te(1e3);else throw Ce}}},K=()=>{N&&Y&&(_([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(V)]),W(N,function(){N=null,O()}))},ie=I=>e.fragUrlTemplate.replace("%%id%%",I.chunkIdx),Re=I=>{h()&&S(ie(I),(ee,Z)=>{if(h()){if(Z/=1e3,N=ee,V=I,o=I.startTS,Z){const te=Math.min(10,I.dur/Z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*te:te}K()}},()=>this._handleNetworkError())},et=I=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(I),!1)))},mt=I=>{h()&&(e.cachedHeader=I,W(I,()=>{Y=!0,K()}))};n=!0,C.seek(I=>{if(h()){if(M=se(),!I){A();return}G=I,!a.isNullable(E)||I.startTS>E?Re(I):(V=I,O())}},E),e.cachedHeader?mt(e.cachedHeader):p(e.headerUrl,mt,()=>this._handleNetworkError())},stop:P,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 p,S,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(S=this._getBufferSizeSec(),f=h/this.bitrate,S>10&&f>.8||S>15&&f>.5||S>20&&f>.3)){e(`Not switching: buffer=${Math.floor(S)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}p=this._selectQuality(h),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(p,S)=>{const f=se();if(this.chunkRateEstimator.addInterval(p,f,S)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:S,duration:f-p,speed:g}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let o=-1/0,c,d=!0;const u=()=>{let h=n.get();if(h&&c&&this.autoQuality){if(d&&h>c&&ks(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,p)=>{const S=n.updateChunk(h,p);return S&&u(),S},notifySwitch:h=>{const p=se();h<c&&(o=p),c=h}}}_fetchManifest(e,t,s){this.manifestRequest=Et(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(bt).withRetryCount(gt).withRetryInterval(Ni,Ii).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;xe(t).then(s=>{s||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params,n=o=>{const c=[];return o?.length?(o.forEach((d,u)=>{d.video&&i.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,c.push(d))}),c.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),c):(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))},xi))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var D;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(D||(D={}));const Oi=[D.PAUSED,D.PLAYING,D.READY],Fi=[D.PAUSED,D.PLAYING,D.READY];class Ui{subscription=new a.Subscription;video;videoState=new j(D.STOPPED);dash;representations$=new a.ValueSubject([]);textTracksManager=new be;maxSeekBackTime$=new a.ValueSubject(1/0);zeroTime$=new a.ValueSubject(void 0);liveOffset=new Ot;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=Pe(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=we(this.video);this.subscription.add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===D.READY&&this.videoState.setState(D.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(D.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===w.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(D.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(He(this.video,this.params.desiredState.isLooped,t)).add(Ae(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:i}})=>{const n=i&&ei(i);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(i=>{switch(i.to){case D.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case D.MANIFEST_READY:case D.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case D.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case D.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.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Vi({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:ht(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(Qe(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=pt(i.name)??Ue(i.video),c=i.bitrate/1e3,d={...i.video};if(!o)continue;const u={id:n,quality:o,bitrate:c,size:d};s.push({track:u,representation:i})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map(({track:i})=>i)),this.videoState.getTransition()?.to===D.MANIFEST_READY&&this.videoState.setState(D.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!==D.STOPPED&&(this.videoState.startTransitionTo(D.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(D.STOPPED));return}if(!t){if(Fi.includes(e)){const o=this.params.desiredState.videoTrack.getTransition()?.to;a.isNonNullable(o)&&this.setVideoTrack(o);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if(i?.to!==exports.PlaybackState.PAUSED&&n.state===w.Requested&&Oi.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case D.STOPPED:this.videoState.startTransitionTo(D.MANIFEST_READY),this.dash.attachSource(Qe(this.params.source.url));return;case D.MANIFEST_READY:this.videoState.startTransitionTo(D.READY),this.prepare();break;case D.READY:if(s===exports.PlaybackState.PAUSED)this.videoState.setState(D.PAUSED);else if(s===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(D.PLAYING);const o=i?.from;o&&o===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(D.PAUSED)})}return;case D.PLAYING:s===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(D.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case D.PAUSED:s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(D.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(D.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(e)}}}}var As=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}},Ve=(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 Hi=r=>{const e=document.createElement("a");return e.href=r,e.origin},Yi=r=>{const e=document.createElement("a");return e.href=r,e.host};class Ps{_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(Yi(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 Pt{_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,c=i.length;o<c;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,c){this.abort(()=>{let d=0;const u=Date.now();let l=0,h=0,p=0;const S=m=>{i(Pt._str2ua(m.substr(d))),d=m.length};let f=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(f=Je(f)),this._lastXhr=new Ps(f,e.failoverHosts,m=>{this._lastXhr=void 0,S(m);const g=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:g,speed:8*m.length/(g/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n?.()},m=>{if(m.length-d>c&&S(m),h===0){h=Date.now();return}p=m.length-l;const g=Date.now()-h;p>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:p,duration:g,speed:8*p/(g/1e3)}),p=0,l=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,g,k)=>this._params.onError(m,g,k))})}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=Pt._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 qi{_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=(c,d)=>{const u=c?parseFloat(c.replace(",",".")):NaN;return(isNaN(u)?0:u)*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=Je(s)),new Ps(s,t,i=>{this.attachManifest(i,t,Hi(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=(u,l)=>{const h=u.attributes.getNamedItem(l);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const c=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{const l=u.getElementsByTagName("SegmentBase")[0],h=l&&o(l,"indexRange").split("-"),p=l&&l.getElementsByTagName("Initialization")[0],S=p&&o(p,"range").split("-");if(!S||!h){const H=u.parentElement;if(H?.getAttribute("contentType")==="text"){const E=u.getAttribute("id")??void 0,y=(s?s+"/":"")+u.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,_=H.getAttribute("lang")??void 0;y&&d.push({id:E,url:y,language:_})}return}const f=.1,m=Number(u.attributes.getNamedItem("bandwidth")?.value),g=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let k;const P=u.attributes.getNamedItem("frameRate")?.value??void 0;k=P?Ft(P):void 0,c.push({width:Number(u.attributes.getNamedItem("width")?.value),height:Number(u.attributes.getNamedItem("height")?.value),bandwidth:m,baseURL:g,failoverHosts:t,indexFrom:Number(h[0]),indexTo:Number(h[1]),initFrom:Number(S[0]),initTo:Number(S[1]),codecs:u.attributes.getNamedItem("codecs")?.value??void 0,mimeType:u.attributes.getNamedItem("mimeType")?.value??void 0,fps:k,bufferSize:f*m/8,bufferLength:f,name:u.attributes.getNamedItem("okQuality")?.value??void 0,id:u.attributes.getNamedItem("id")?.value??void 0})}),c.length)this._representations=c;else{this._onDashCallback("error");return}d.forEach(({id:u,language:l,url:h})=>{const p=document.createElement("track");p.setAttribute("src",h),u&&p.setAttribute("id",u),l&&p.setAttribute("srclang",l),this._video.appendChild(p)}),this._representations.sort((u,l)=>l.bandwidth-u.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 c=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const l=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let p=0;p<l;p+=1){const S=u+(o.getUint32(n,!1)&2147483647),f=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/c,toTime:f/c,fromOffset:u,toOffset:S-1}),u=S,d=f}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 u=this._findRef(this._video.currentTime);if(!u||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(u.fromTime)];l!==i&&(i=l,this._params.onRepresentationPlay(l));let h;if(this._findRef(u.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 f=this._buffer.getNextWithGap(S);f&&(this._video.currentTime=f.from)}catch(f){throw this._params.onError("GapSyncError",`Seek Error ${String(f)}`,f),f}},h*1e3)))}},c=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}c()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Pt({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||c(),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 u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-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),c=Math.abs(this._video.currentTime-t),d=i||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||c<=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,c)=>this._stream.append(o,c),()=>{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,(c,d)=>this._stream.remove(c,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(i.fromTime-n,i.toTime+n,(c,d)=>this._stream.remove(c,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 ji=[x.PAUSED,x.PLAYING];class Gi{videoState=new j(x.STOPPED);subscription=new a.Subscription;video;buffer;dash;representations$=new a.ValueSubject([]);currentRepresentation$=new a.ValueSubject(void 0);params;textTracksManager=new be;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=Pe(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 mi(this.video),this.dash=new qi({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=c=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:c})},i=()=>{const c=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:c},n=we(this.video),o=(c,d)=>this.subscription.add(c.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(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==w.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(He(this.video,t.isLooped,s)),this.subscription.add(Ae(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(At(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(c=>{this.buffer.fill(),e.currentBuffer$.next(c)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:c,message:d,thrown:u})=>({id:`DashLite_${c}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).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 c=this.currentRepresentation$.getValue(),d=this.representations$.getValue(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.videoTrack.getState(),h=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=i();u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to);let f;if(!S&&a.isNonNullable(l))f=l;else{const m=Ve(this.video.buffered,this.video.currentTime*1e3),g=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,k=Math.min(m/g,1);f=ht(d.map(({track:P})=>P),{container:p,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:k,playbackRate:this.video.playbackRate,current:d.find(({representation:P})=>P===c)?.track})?.id}return a.isNonNullable(f)?d.find(({track:m})=>m.id===f)?.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,s)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(c=>c.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((c,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&i()?c.height<=d.height:c===d)).subscribe(c=>{const d=Ve(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!i())&&(this.dash.setQualityByRepresentation(c,!0),this.params.output.hostname$.next(ae(c.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(c=>{const{type:d,reused:u}=As(c);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(c=>this.params.dependencies.throughputEstimator.addRawRtt(c))).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.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return 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&&pt(s.name))??Ue(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const u={id:i,quality:n,bitrate:o,size:c,fps:d};t.push({track:u,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(){xe(this.video).then(e=>{e||(this.videoState.setState(x.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(x.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(i?.to!==exports.PlaybackState.PAUSED&&n.state===w.Requested&&ji.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 ce;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(ce||(ce={}));var wt;(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"})(wt||(wt={}));var ue;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(ue||(ue={}));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 Xe;(function(r){r.MP4="mp4",r.WEBM="webm"})(Xe||(Xe={}));var $t;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})($t||($t={}));var Mt=(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 zi=(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)},Qi=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Wt=Qi?zi:window.requestIdleCallback;let ws=!1;try{ws=Es()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class Wi{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;ws&&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)}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"&&t==="remove"||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 Jt=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};class ge{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class $s extends ge{}class Ji extends ge{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class Xi extends ge{parseChildrenBoxes(){return Ze(this.content)}}class Ki extends ge{data;constructor(e){super(e),this.data=this.content}}class ft extends ge{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Zi extends ft{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const i=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const c=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:i,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:d})}}}class ea extends ge{parseChildrenBoxes(){return Ze(this.content)}}class ta extends ge{parseChildrenBoxes(){return Ze(this.content)}}var Me;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Me||(Me={}));class sa extends ft{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Me.MONOSCOPIC;break;case 1:this.stereoMode=Me.TOP_BOTTOM;break;case 2:this.stereoMode=Me.LEFT_RIGHT;break;case 3:this.stereoMode=Me.STEREO_CUSTOM;break;case 4:this.stereoMode=Me.RIGHT_LEFT;break}this.cursor+=1}}class ia extends ft{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class aa extends ft{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class ra extends ge{parseChildrenBoxes(){return Ze(this.content)}}class na extends ft{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class oa extends ge{parseChildrenBoxes(){return Ze(this.content)}}class ca extends ge{parseChildrenBoxes(){return Ze(this.content)}}const ua={ftyp:Ji,moov:Xi,mdat:Ki,sidx:Zi,trak:ea,mdia:ra,tkhd:na,minf:oa,sv3d:ta,st3d:sa,prhd:ia,proj:ca,equi:aa,unknown:$s};class da{createBox(e,t){const s=ua[e];return s?new s(t):new $s(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ct.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Ct=new da;function ot(r,e){const t=new TextDecoder("ascii");let s=r.byteOffset,i=[];for(;s<r.byteLength;){const n=t.decode(new DataView(r.buffer,s,1));if(n===e[i.length]?i.push(n):i=[],i.length===4&&i.join("")===e){const c=new DataView(r.buffer,s-7,4).getUint32(0);return s-7+c>r.byteLength?null:Ct.createBox(e,new DataView(r.buffer,s-7))}s++}return null}function la(r,e){const t=[];let s=r.byteOffset;for(;s<r.byteLength;){const i=ot(new DataView(r.buffer,s,r.byteLength),e);if(i)t.push(i),s+=i.source.byteOffset+i.source.byteLength;else break}return t}function Ze(r){const e=[];let t=0;for(;t<r.byteLength;){const s=Ct.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const ha=new TextDecoder("ascii"),pa=r=>ha.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",fa=r=>{const e=Ct.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,s=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,c={status:B.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,c})},ma=r=>{const e=la(r,"mdat");if(e.length){const t=e.reduce((s,i)=>s+i.size,0);return new DataView(r.buffer,r.byteOffset,t)}return null},Sa=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:$t.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ot(r,"sv3d")){e.is3dVideo=!0;const s=ot(r,"st3d");s&&(e.stereoMode=s.stereoMode);const i=ot(r,"prhd");i&&(e.projectionData.pose.yaw=i.poseYawDegrees,e.projectionData.pose.pitch=i.posePitchDegrees,e.projectionData.pose.roll=i.poseRollDegrees);const n=ot(r,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},ba={validateData:pa,parseInit:Sa,getIndexRange:()=>{},parseSegments:fa,parseFeedableSegmentChunk:ma};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.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",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 v;(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"})(v||(v={}));const Xt={[b.EBML]:{type:v.Master},[b.EBMLVersion]:{type:v.UnsignedInteger},[b.EBMLReadVersion]:{type:v.UnsignedInteger},[b.EBMLMaxIDLength]:{type:v.UnsignedInteger},[b.EBMLMaxSizeLength]:{type:v.UnsignedInteger},[b.DocType]:{type:v.String},[b.DocTypeVersion]:{type:v.UnsignedInteger},[b.DocTypeReadVersion]:{type:v.UnsignedInteger},[b.Void]:{type:v.Binary},[b.Segment]:{type:v.Master},[b.SeekHead]:{type:v.Master},[b.Seek]:{type:v.Master},[b.SeekID]:{type:v.Binary},[b.SeekPosition]:{type:v.UnsignedInteger},[b.Info]:{type:v.Master},[b.TimestampScale]:{type:v.UnsignedInteger},[b.Duration]:{type:v.Float},[b.Tracks]:{type:v.Master},[b.TrackEntry]:{type:v.Master},[b.Video]:{type:v.Master},[b.Projection]:{type:v.Master},[b.ProjectionType]:{type:v.UnsignedInteger},[b.ProjectionPrivate]:{type:v.Master},[b.Chapters]:{type:v.Master},[b.Cluster]:{type:v.Master},[b.Timestamp]:{type:v.UnsignedInteger},[b.SilentTracks]:{type:v.Master},[b.SilentTrackNumber]:{type:v.UnsignedInteger},[b.Position]:{type:v.UnsignedInteger},[b.PrevSize]:{type:v.UnsignedInteger},[b.SimpleBlock]:{type:v.Binary},[b.BlockGroup]:{type:v.Master},[b.EncryptedBlock]:{type:v.Binary},[b.Attachments]:{type:v.Master},[b.Tags]:{type:v.Master},[b.Cues]:{type:v.Master},[b.CuePoint]:{type:v.Master},[b.CueTime]:{type:v.UnsignedInteger},[b.CueTrackPositions]:{type:v.Master},[b.CueTrack]:{type:v.UnsignedInteger},[b.CueClusterPosition]:{type:v.UnsignedInteger},[b.CueRelativePosition]:{type:v.UnsignedInteger},[b.CueDuration]:{type:v.UnsignedInteger},[b.CueBlockNumber]:{type:v.UnsignedInteger},[b.CueCodecState]:{type:v.UnsignedInteger},[b.CueReference]:{type:v.Master},[b.CueRefTime]:{type:v.UnsignedInteger}},Rs=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=Rt(r,t),i=s in Xt,n=i?Xt[s].type:v.Binary,o=r.getUint8(t);let c=0;o&128?c=1:o&64?c=2:o&32?c=3:o&16?c=4:o&8?c=5:o&4?c=6:o&2?c=7:o&1&&(c=8);const d=new DataView(r.buffer,r.byteOffset+t+1,c-1),u=o&255>>c,l=Rt(d),h=u*2**((c-1)*8)+l,p=t+c;let S;return p+h>r.byteLength?S=new DataView(r.buffer,r.byteOffset+p):S=new DataView(r.buffer,r.byteOffset+p,h),{tag:i?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:p,tagSize:p+h,value:S,valueSize:h}},Rt=(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},me=(r,e)=>{switch(e){case v.SignedInteger:return r.getInt8(0);case v.UnsignedInteger:return Rt(r);case v.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case v.String:return new TextDecoder("ascii").decode(r);case v.UTF8:return new TextDecoder("utf-8").decode(r);case v.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case v.Master:return r;case v.Binary:return r;default:a.assertNever(e)}},Ke=(r,e)=>{let t=0;for(;t<r.byteLength;){const s=new DataView(r.buffer,r.byteOffset+t),i=Rs(s);if(!e(i))return;i.type===v.Master&&Ke(i.value,e),t=i.value.byteOffset-r.byteOffset+i.valueSize}},ga=r=>{if(r.getUint32(0)!==b.EBML)return!1;let e,t,s;const i=Rs(r);return Ke(i.value,({tag:n,type:o,value:c})=>(n===b.EBMLReadVersion?e=me(c,o):n===b.DocType?t=me(c,o):n===b.DocTypeReadVersion&&(s=me(c,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Ds=[b.Info,b.SeekHead,b.Tracks,b.TrackEntry,b.Video,b.Projection,b.ProjectionType,b.ProjectionPrivate,b.Chapters,b.Cluster,b.Cues,b.Attachments,b.Tags],ya=[b.Timestamp,b.SilentTracks,b.SilentTrackNumber,b.Position,b.PrevSize,b.SimpleBlock,b.BlockGroup,b.EncryptedBlock],Ta=r=>{let e,t,s,i,n=!1,o=!1,c=!1,d,u,l=!1;const h=0;return Ke(r,({tag:p,type:S,value:f,valueSize:m})=>{if(p===b.SeekID){const g=me(f,S);u=Rt(g)}else p!==b.SeekPosition&&(u=void 0);return p===b.Segment?(e=f.byteOffset,t=f.byteOffset+m):p===b.Info?n=!0:p===b.SeekHead?o=!0:p===b.TimestampScale?s=me(f,S):p===b.Duration?i=me(f,S):p===b.SeekPosition&&u===b.Cues?d=me(f,S):p===b.Tracks?Ke(f,({tag:g,type:k,value:P})=>g===b.ProjectionType?(l=me(P,k)===1,!1):!0):n&&o&&Ds.includes(p)&&(c=!0),!c}),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,is3dVideo:l,stereoMode:h,projectionType:$t.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ea=r=>{if(a.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},va=(r,e)=>{let t=!1,s=!1;const i=c=>a.isNonNullable(c.time)&&a.isNonNullable(c.position),n=[];let o;return Ke(r,({tag:c,type:d,value:u})=>{switch(c){case b.Cues:t=!0;break;case b.CuePoint:o&&i(o)&&n.push(o),o={};break;case b.CueTime:o&&(o.time=me(u,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:o&&(o.position=me(u,d));break;default:t&&Ds.includes(c)&&(s=!0)}return!(t&&s)}),o&&i(o)&&n.push(o),n.map((c,d)=>{const{time:u,position:l}=c,h=n[d+1];return{status:B.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},ka=r=>{let e=0,t=!1;try{Ke(r,s=>s.tag===b.Cluster?s.tagSize<=r.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):ya.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},Aa={validateData:ga,parseInit:Ta,getIndexRange:Ea,parseSegments:va,parseFeedableSegmentChunk:ka};class Kt{onLastSegment$=new a.ValueSubject(!1);fullyBuffered$=new a.ValueSubject(!1);playingRepresentation$=new a.ValueSubject(void 0);playingRepresentationInit$=new a.ValueSubject(void 0);error$=new a.Subject;gaps=[];subscription=new a.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Oe;destroyAbortController=new Oe;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;constructor(e,t,s,i,{fetcher:n,tuning:o,getCurrentPosition:c,compatibilityMode:d=!1}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=c,this.container=s,s){case Xe.MP4:this.containerParser=ba;break;case Xe.WEBM:this.containerParser=Aa;break;default:a.assertNever(s)}this.initData=new Map(i.map(u=>[u.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(u=>[u.id,u])),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 Wi(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},c=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:c}))),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(c=>{if(!this.sourceBuffer)return;const d=Math.min(this.bufferLimit,Jt(this.sourceBuffer.buffered)*.8);this.bufferLimit=d,this.pruneBuffer(this.getCurrentPosition(),c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(c=>this.error$.next(c))),yield this.loadInit(t,"high",!0);const s=this.initData.get(t.id),i=this.segments.get(t.id),n=this.parsedInitData.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 o=0;for(const c of i)c.time.from-o>0&&this.gaps.push({representation:t.id,from:o,to:c.time.from}),o=c.time.to;a.isNonNullable(t.duration)&&t.duration-o>0&&this.gaps.push({representation:t.id,from:o,to:t.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n)}.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 Oe,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(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Ve(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)&&Jt(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ve(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<l);return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(s,t.segmentReference.type,n),c.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(c.includes(i))u="high";else{const l=c.at(0);l&&l.time.from-i.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(c,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status===B.FED&&!c.length&&Ve(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=s.at(-1);d&&d.status===B.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(){this.initData.clear(),this.segments.clear(),this.parsedInitData.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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex(({status:h,time:{from:p,to:S}},f)=>{const m=p<=s&&S>=s,g=p>s||m||f===0&&s===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=s+k||S<=s+k;return(h===B.NONE||h===B.PARTIALLY_EJECTED&&g&&P&&this.sourceBuffer&&!Mt(this.sourceBuffer.buffered,s))&&g&&P});if(i===-1)return[];if(t!==ue.BYTE_RANGE)return e.slice(i,i+1);const n=e;let o=0,c=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let h=i;h<n.length&&(o<=u||c<=l);h++){const p=n[h];if(o+=p.byte.to+1-p.byte.from,c+=p.time.to+1-p.time.from,p.status===B.NONE||p.status===B.PARTIALLY_EJECTED)d.push(p);else break}return d}async loadSegments(e,t,s="auto"){if(!e.length)return;let i,n,o=e;const{type:c}=t.segmentReference;switch(c){case ue.BYTE_RANGE:{i=t.segmentReference.url,n={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case ue.TEMPLATE:{const u=e.at(0);i=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(c)}for(const u of o)u.status=B.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await a.abortable(d,async function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(i,{range:n,onProgress:(u,l)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,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,u=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(u)})}onSegmentDownloadError(e){let t=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(t=Ve(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()},c=h=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=B.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const S of this.segments.get(p.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 u=d.segmentReference.type,l=e.byteLength;for(const h of this.activeSegments){const{segment:p}=h,S=u===ue.BYTE_RANGE,f=S?p.byte.to-p.byte.from+1:l;if(h.representationId!==t||!(!S||p.byte.from>=s&&p.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const g=S?p.byte.from-s:0,k=S?p.byte.to-s:e.byteLength,P=g<i,H=k<=i;if(p.status===B.DOWNLOADING&&P&&H){p.status=B.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+g,f);this.sourceBufferTaskQueue.append(E,n).then(y=>y&&!n.aborted?c(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&P&&(h.loadedBytes=Math.min(f,i-g),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),y=h.loadedBytes===f?E:this.containerParser.parseFeedableSegmentChunk(E);y?.byteLength&&(p.status=B.PARTIALLY_FED,h.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,n).then(_=>{if(n.aborted)o();else if(_)h.fedBytes+=y.byteLength,h.fedBytes===f&&c(h);else{if(h.feedingBytes<f)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[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=Wt(()=>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 c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,i)).then(c=>{if(!c)return;const{init:d,dataView:u,segments:l}=c,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,l),this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,c=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:c})});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,c=!1;const d=u=>{n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const l="size"in u?u.size??0:u.byte.to-u.byte.from;i+=l};for(const u of this.segments.values())for(const l of u){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status===B.FED&&d(l)}if(c=isFinite(n)&&isFinite(o),!c){i=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const l of u){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status===B.FED&&d(l)}}if(c=isFinite(n)&&isFinite(o),!c)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const l=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const p of this.segments.values())for(const S of p)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(c=isFinite(n)&&isFinite(o),!c&&s){i=0,n=1/0,o=-1/0;const u=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+u&&h.status===B.FED&&d(h)}return c=isFinite(n)&&isFinite(o),c?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,c=this.sourceBuffer.buffered.end(n)*1e3;if(!(c<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&c>=s.time.to){i=void 0;break}c>s.time.from&&c<s.time.to&&(i.from=c),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=Wt(()=>{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!==B.FED&&n!==B.PARTIALLY_EJECTED)continue;const o=Math.floor(i.time.from),c=Math.ceil(i.time.to),d=e.some(l=>l.from-t<=o&&l.to+t>=c),u=e.filter(l=>o>=l.from-t&&o<=l.to+t||c>=l.from-t&&c<=l.to+t);d||(u.length===1?i.status=B.PARTIALLY_EJECTED:i.status=B.NONE)}}}var Ge;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Ge||(Ge={}));class Pa{throughputEstimator;requestQuic;lastConnectionType$=new a.ValueSubject(void 0);lastConnectionReused$=new a.ValueSubject(void 0);lastRequestFirstBytes$=new a.ValueSubject(void 0);abortAllController=new Oe;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}=As(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=a.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Je(t));const s=yield We(t,{signal:this.abortAllController.signal}).catch(nt);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=a.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Ge.HEADER:Ge.PARAM,range:s,onProgress:i,priority:n="auto",signal:o,measureThroughput:c=!0}={}){let d=e;const u=new Headers;if(s)switch(t){case Ge.HEADER:{u.append("Range",`bytes=${s.from}-${s.to}`);break}case Ge.PARAM:{const N=new URL(d,location.href);N.searchParams.append("bytes",`${s.from}-${s.to}`),d=N.toString();break}default:a.assertNever(t)}this.requestQuic&&(d=Je(d));let l=this.abortAllController.signal;if(o){const N=new Oe;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(o,"abort")).subscribe(()=>{try{N.abort()}catch(V){nt(V)}})),this.abortAllController.signal.aborted||o.aborted)try{N.abort()}catch(V){nt(V)}l=N.signal}const h=a.now(),p=yield We(d,{priority:n,headers:u,signal:l}).catch(nt),S=a.now();if(this.throughputEstimator?.addRawRtt(S-h),!p)return null;if(!p.ok||!p.body)return Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const f=parseInt(p.headers.get("Content-Length")??"",10)||s&&s.to-s.from+1||NaN;if(!f){const N=yield p.arrayBuffer();return this.throughputEstimator?.addRawSpeed(N.byteLength,a.now()-S),i?.(new DataView(N),N.byteLength),N}if(!i&&!c)return p.arrayBuffer();const[m,g]=p.body.tee(),k=m.getReader();c&&this.throughputEstimator?.trackStream(g);let P=0;const H=new ArrayBuffer(f),E=new Uint8Array(H),y=new DataView(H);let _=!1;const C=N=>{_=!0,nt(N)},Y=a.abortable(l,async function*({done:N,value:V}){P===0&&this.lastRequestFirstBytes$.next(a.now()-h),!l.aborted&&(N?i?.(y,P):V&&(E.set(V,P),P+=V.byteLength,i?.(y,P),yield k?.read().then(Y,C)))}.bind(this));return yield k?.read().then(Y,C),_?null:H}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:i}=e;switch(i){case ue.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case ue.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!==ue.BYTE_RANGE)return null;const{from:i,to:n}=e.initRange;let o=i,c=n,d=!1,u,l;e.indexRange&&(u=e.indexRange.from,l=e.indexRange.to,d=n+1===u,d&&(o=Math.min(u,i),c=Math.max(l,n))),o=Math.min(o,0);const h=yield this.fetch(e.url,{range:{from:o,to:c},priority:s,measureThroughput:!1});if(!h)return null;const p=new DataView(h,i-o,n-o+1);if(!t.validateData(p))throw new Error("Invalid media file");const S=t.parseInit(p),f=e.indexRange??t.getIndexRange(S);if(!f)throw new ReferenceError("No way to load representation index");let m;if(d)m=new DataView(h,f.from-o,f.to-f.from+1);else{const k=yield this.fetch(e.url,{range:f,priority:s,measureThroughput:!1});if(!k)return null;m=new DataView(k)}const g=t.parseSegments(m,S,f);return{init:S,dataView:new DataView(h),segments:g}}.bind(this));fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==ue.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});if(!i)return null;const n=e.segments.map(o=>({...o,status:B.NONE,size:void 0}));return{init:{},segments:n,dataView:new DataView(i)}}.bind(this))}const nt=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},Zt=r=>{if(!r.startsWith("P"))return;const e=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},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},It=(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,(c,d)=>a.isNullable(n)?c:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},wa=(r,e)=>{const s=new DOMParser().parseFromString(r,"application/xml"),i={video:[],audio:[],text:[]},n=s.children[0],o=n.getElementsByTagName("Period")[0],c=o.children;let d;const u=n.getAttribute("mediaPresentationDuration"),l=o.getAttribute("duration");if(u)d=Zt(u);else if(l){const f=Zt(l);a.isNonNullable(f)&&(d=f)}let h=0;const p=n.getAttribute("profiles")?.split(",")??[],S=p.includes(wt.WEBM_AS_IN_FFMPEG)||p.includes(wt.WEBM_AS_IN_SPEC)?Xe.WEBM:Xe.MP4;for(const f of c){const m=f.getAttribute("mimeType"),g=f.getAttribute("codecs"),k=f.getAttribute("contentType")??m?.split("/")[0],P=f.getAttribute("profiles")?.split(",")??[],H=f.querySelectorAll("Representation"),E=f.querySelector("SegmentTemplate");if(k!=="text")for(const y of H){const _=y.getAttribute("mimeType")??m,C=y.getAttribute("codecs")??g??"",Y=y.getAttribute("contentType")??_?.split("/")[0]??k,N=f.getAttribute("profiles")?.split(",")??[],V=parseInt(y.getAttribute("width")??"",10),G=parseInt(y.getAttribute("height")??"",10),M=parseInt(y.getAttribute("bandwidth")??"",10)/1e3,J=y.getAttribute("frameRate")??"",pe=y.getAttribute("quality")??void 0,$e=J?Ft(J):void 0,A=y.getAttribute("id")??(h++).toString(10),O=Y==="video"?`${G}p`:Y==="audio"?`${M}Kbps`:C,W=`${A}@${O}`,K=y.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(K,e).toString(),Re=[...p,...P,...N];let et;const mt=y.querySelector("SegmentBase"),I=y.querySelector("SegmentTemplate")??E;if(mt){const Z=y.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[te,ye]=Z.split("-").map(Le=>parseInt(Le,10)),Te={from:te,to:ye},le=y.querySelector("SegmentBase")?.getAttribute("indexRange"),[De,_e]=le?le.split("-").map(Le=>parseInt(Le,10)):[],Ce=le?{from:De,to:_e}:void 0;et={type:ue.BYTE_RANGE,url:ie,initRange:Te,indexRange:Ce}}else if(I){const Z={representationId:y.getAttribute("id")??void 0,bandwidth:y.getAttribute("bandwidth")??void 0},te=parseInt(I.getAttribute("timescale")??"",10),ye=I.getAttribute("initialization")??"",Te=I.getAttribute("media"),le=parseInt(I.getAttribute("startNumber")??"",10)??1,De=It(ye,Z);if(!Te)throw new ReferenceError("No media attribute in SegmentTemplate");const _e=I.querySelectorAll("SegmentTimeline S")??[],Ce=[];if(_e.length){let Le=le,Be=0;for(const tt of _e){const Ye=parseInt(tt.getAttribute("d")??"",10)*1e3,st=parseInt(tt.getAttribute("r")??"",10)||0,it=parseInt(tt.getAttribute("t")??"",10)??void 0;for(let Ht=0;Ht<st+1;Ht++){const Ls=It(Te,{...Z,segmentNumber:Le.toString(10),segmentTime:it.toString(10)}),Bs=it?it/te:Be;Be+=Ye/te;const Ms=Be;Le++,Ce.push({time:{from:Bs,to:Ms},url:Ls})}}}else if(a.isNonNullable(d)){const Be=parseInt(I.getAttribute("duration")??"",10)/te*1e3,tt=Math.ceil(d/Be);let Ye=0;for(let st=1;st<tt;st++){const it=It(Te,{...Z,segmentNumber:st.toString(10),segmentTime:Ye.toString(10)});Ce.push({time:{from:Ye,to:Ye+Be},url:it}),Ye+=Be}}et={type:ue.TEMPLATE,baseUrl:ie,initUrl:De,segments:Ce}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Y||!_)continue;const ee={video:ce.VIDEO,audio:ce.AUDIO,text:ce.TEXT}[Y];ee&&i[ee].push({id:W,kind:ee,segmentReference:et,profiles:Re,duration:d,bitrate:M,mime:_,codecs:C,width:V,height:G,fps:$e,quality:pe})}}return{duration:d,container:S,representations:i}},$a=["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 Ra=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new a.Subscription;fetcher;state$=new j(oe.NONE);currentVideoRepresentation$=new a.ValueSubject(void 0);currentVideoRepresentationInit$=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 Oe;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Pa({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=wa(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:c})=>Boolean(e.canPlayType?.(o)&&window.MediaSource?.isTypeSupported?.(`${o}; codecs="${c}"`));this.manifest={...i,representations:Object.fromEntries(Object.entries(i.representations).map(([o,c])=>[o,c.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 Kt(ce.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(t)&&(this.audioBufferManager=new Kt(ce.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:c})=>o&&c))).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.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),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(...$a.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&&Mt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[ce.VIDEO]:this.videoBufferManager,[ce.AUDIO]:this.audioBufferManager,[ce.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),Mt(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=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}}};const Da=135,_a=76;class Ca{fov;rotation;constructor(){this.fov={x:Da,y:_a},this.rotation={x:0,y:0,z:0}}}const qe=10,es=175;class Na{options;camera;rotating=!1;torqueLossTS=0;hold=!1;lastTick;rotationSpeed;rotationMoment;constructor(e,t={}){this.options=t,this.camera=e,this.torqueLossTS=performance.now(),this.rotationSpeed={x:0,y:0,z:0},this.rotationMoment={x:0,y:0,z:0}}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.rotation.x+e,this.camera.rotation.y+t,this.camera.rotation.z+s)}pointCameraTo(e=0,t=0,s=0){this.camera.rotation.x=e,this.camera.rotation.y=this.limitCameraRotationY(t),this.camera.rotation.z=s}setRotationSpeed(e,t,s){e===void 0&&(e=this.rotationSpeed.x),t===void 0&&(t=this.rotationSpeed.y),s===void 0&&(s=this.rotationSpeed.z),this.rotationSpeed.x=e,this.rotationSpeed.y=t,this.rotationSpeed.z=s,this.torqueLossTS=performance.now()}startRotation(){this.rotating=!0}stopRotation(e=!1){e&&this.setRotationSpeed(0,0,0),this.rotating=!1,this.torqueLossTS=performance.now()}limitCameraRotationY(e){return Math.max(-es,Math.min(e,es))}temporalFn(e){const t=100-5e-4*(e-this.torqueLossTS);return Math.sign(t)*Math.sqrt(Math.abs(t))/10}tick(e){if(!this.lastTick){this.lastTick=e;return}const s=(e-this.lastTick)/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*s*qe,this.rotationSpeed.y*s*qe,this.rotationSpeed.z*s*qe);else{let i=0,n=0,o=0;const c=this.temporalFn(e);this.rotationSpeed.x&&(this.rotationSpeed.x=Math.sign(this.rotationSpeed.x)*Math.max(Math.abs(this.rotationSpeed.x)-c,0),i=this.rotationSpeed.x*s*qe),this.rotationSpeed.y&&(this.rotationSpeed.y=Math.sign(this.rotationSpeed.y)*Math.max(Math.abs(this.rotationSpeed.y)-c,0),n=this.rotationSpeed.y*s*qe),this.rotationSpeed.z&&(this.rotationSpeed.z=Math.sign(this.rotationSpeed.z)*Math.max(Math.abs(this.rotationSpeed.z)-c,0),o=this.rotationSpeed.z*s*qe),this.turnCamera(i,n,o)}this.rotationSpeed.x===0&&this.rotationSpeed.y===0&&this.rotationSpeed.z===0&&this.stopRotation(),this.lastTick=e}}const Ia=`
|
|
8
|
+
attribute vec2 a_vertex;
|
|
9
|
+
attribute vec2 a_texel;
|
|
10
|
+
|
|
11
|
+
varying vec2 v_texel;
|
|
12
|
+
|
|
13
|
+
void main(void) {
|
|
14
|
+
// direct vertex drawing
|
|
15
|
+
gl_Position = vec4(a_vertex, 0.0, 1.0);
|
|
16
|
+
// save texel vector to pass to fragment shader
|
|
17
|
+
v_texel = a_texel;
|
|
18
|
+
}
|
|
19
|
+
`,xa=`
|
|
20
|
+
#ifdef GL_ES
|
|
21
|
+
precision highp float;
|
|
22
|
+
precision highp int;
|
|
23
|
+
#else
|
|
24
|
+
precision mediumhp float;
|
|
25
|
+
#endif
|
|
26
|
+
|
|
27
|
+
varying vec2 v_texel; // [0..1, 0..1]
|
|
28
|
+
|
|
29
|
+
uniform sampler2D u_texture;
|
|
30
|
+
uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
|
|
31
|
+
|
|
32
|
+
const float PI = 3.14159265358979323846264;
|
|
33
|
+
const float PI_2 = PI * 0.5;
|
|
34
|
+
const float PI2 = PI * 2.0;
|
|
35
|
+
|
|
36
|
+
void main(void) {
|
|
37
|
+
// center point of output projection
|
|
38
|
+
float lambda0 = u_focus.x / 360.0; // [-0.5, 0.5]
|
|
39
|
+
float phi0 = u_focus.y / 180.0; // [-0.5, 0.5]
|
|
40
|
+
|
|
41
|
+
float x = PI2 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
|
|
42
|
+
float y = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
|
|
43
|
+
|
|
44
|
+
float p = sqrt(x * x + y * y); // rou
|
|
45
|
+
float c = atan(p);
|
|
46
|
+
float cos_c = cos(c);
|
|
47
|
+
float sin_c = sin(c);
|
|
48
|
+
|
|
49
|
+
// geo coordinates of projection
|
|
50
|
+
float lambda = lambda0 + atan(
|
|
51
|
+
x * sin_c,
|
|
52
|
+
p * cos(phi0) * cos_c - y * sin(phi0) * sin_c
|
|
53
|
+
);
|
|
54
|
+
float phi = asin(cos_c * sin(phi0) + (y * sin_c * cos(phi0)) / p);
|
|
55
|
+
|
|
56
|
+
// reprojected texture coordinates
|
|
57
|
+
vec2 tc = vec2(
|
|
58
|
+
mod(lambda / PI2 - 0.5, 1.0), // [0..1]
|
|
59
|
+
mod(phi / PI - 0.5, 1.0) // [0..1]
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
// sample using new coordinates
|
|
63
|
+
gl_FragColor = texture2D(u_texture, tc);
|
|
64
|
+
}
|
|
65
|
+
`;class La{container;sourceVideoElement;canvas;gl;options;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;lastCameraRotationX=0;lastCameraRotationY=0;lastCameraRotationT=0;lastCameraRotationDX=0;lastCameraRotationDY=0;mouseDown=!1;onMouseDownHandlerFn;onMouseMoveHandlerFn;onMouseUpHandlerFn;mouseLeaveHandlerFn;renderFn;active=!1;constructor(e,t,s={}){this.container=e,this.sourceVideoElement=t,this.options=s,this.canvas=document.createElement("canvas");const i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.canvas.classList.add("player-scene3d"),this.container.appendChild(this.canvas),this.camera=new Ca,this.cameraRotationManager=new Na(this.camera),this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.onMouseDownHandlerFn=this.mouseDownHandler.bind(this),this.onMouseMoveHandlerFn=this.mouseMoveHandler.bind(this),this.onMouseUpHandlerFn=this.mouseUpHandler.bind(this),this.mouseLeaveHandlerFn=this.mouseLeaveHandler.bind(this),this.initControls(),this.renderFn=this.render.bind(this)}play(){this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",()=>{this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.videoInitialized=!0,this.doPlay()})}stop(){this.active=!1}startCameraRotation(e,t,s){this.cameraRotationManager.setRotationSpeed(e,t,s),this.cameraRotationManager.startRotation()}stopCameraRotation(e=!1){this.cameraRotationManager.stopRotation(e)}destroy(e){this.stop(),this.container.removeEventListener("mousedown",this.onMouseDownHandlerFn),this.container.removeEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.removeEventListener("mouseup",this.onMouseUpHandlerFn),this.canvas.remove(),e?.()}doPlay(){this.active=!0,requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateViewportSize(),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(n,-this.camera.rotation.x,-this.camera.rotation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Ia,this.gl.VERTEX_SHADER),s=this.createShader(xa,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:s=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.rotation.x/360,t=.5-this.camera.rotation.y/180,s=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,n=e-s,o=t-i,c=e+s,d=t-i,u=e+s,l=t+i,h=e-s,p=t+i;return[n,o,c,d,u,l,h,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateViewportSize(){this.frameWidth=this.sourceVideoElement.videoWidth||this.sourceVideoElement.width,this.frameHeight=this.sourceVideoElement.videoHeight||this.sourceVideoElement.height,this.viewportWidth=this.sourceVideoElement.offsetWidth,this.viewportHeight=this.sourceVideoElement.offsetHeight,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}initControls(){this.container.addEventListener("mousedown",this.onMouseDownHandlerFn),this.container.addEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.addEventListener("mouseup",this.onMouseUpHandlerFn),this.container.addEventListener("mouseleave",this.mouseLeaveHandlerFn)}mouseDownHandler(e){e.target===this.canvas&&(this.cameraRotationManager.stopRotation(!0),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationT=e.timeStamp,this.mouseDown=!0)}mouseMoveHandler(e){if(this.mouseDown){const t=e.offsetX-this.lastCameraRotationX,s=this.lastCameraRotationY-e.offsetY;this.cameraRotationManager.pointCameraTo(this.camera.rotation.x+t,this.camera.rotation.y+s),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationDX=t,this.lastCameraRotationDY=s,this.lastCameraRotationT=e.timeStamp}}mouseUpHandler(e){this.mouseDown=!1;const t=e.timeStamp-this.lastCameraRotationT;this.cameraRotationManager.setRotationSpeed(this.lastCameraRotationDX*40/t,this.lastCameraRotationDY*40/t)}mouseLeaveHandler(){this.mouseDown=!1,this.lastCameraRotationX=this.lastCameraRotationY=0}}var z;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(z||(z={}));const Ba=({id:r,width:e,height:t,bitrate:s,fps:i,quality:n})=>{const o=(n?pt(n):void 0)??Ue({width:e,height:t});return o&&{id:r,quality:o,bitrate:s,size:{width:e,height:t},fps:i}},Ma=({id:r,bitrate:e})=>({id:r,bitrate:e}),Va=(r,e,t)=>{const s=e.indexOf(t);return r.at(Math.round(r.length*s/e.length))??r.at(-1)};class Oa{subscription=new a.Subscription;videoState=new j(z.STOPPED);video;scene3D;player;params;elementSize$=new a.ValueSubject(void 0);textTracksManager=new be;videoTracks=[];audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ki;constructor(e){this.params=e,this.video=Pe(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 Ra({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=we(this.video),i=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,l)=>this.subscription.add(u.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(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(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(He(this.video,t.isLooped,i)),this.subscription.add(Ae(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ie(this.video,t.playbackRate,s.playbackRateState$,i)),n(At(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:u})=>{if(u===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((f,m)=>m.bitrate-f.bitrate),p=Array.from(l.video).sort((f,m)=>m.bitrate-f.bitrate);if(!this.params.tuning.isAudioDisabled)for(const f of h){const m=Ma(f);m&&this.audioTracks.push({track:m,representation:f})}for(const f of p){const m=Ba(f);if(m){this.videoTracks.push({track:m,representation:f});const g=!this.params.tuning.isAudioDisabled&&Va(h,p,f);g&&this.audioRepresentations.set(f.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:f})=>f)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:f})=>f)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,this.audioRepresentations.get(S.id)?.id)}else u===oe.REPRESENTATIOS_READY&&(this.videoState.setState(z.READY),this.player.initBuffer())},i));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});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 u=this.player.state$.getState(),l=this.player.state$.getTransition();if(u!==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(ce.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(ce.AUDIO,p.id).catch(o)}},i)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>u&&this.videoTracks.find(({representation:{id:l}})=>l===u)?.track)).subscribe(e.currentVideoTrack$,i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u)if(u.is3dVideo)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch{}else this.destroy3DScene(),e.is3DVideo$.next(!1)},i)),this.params.desiredState.cameraRotation.stateChangeEnded$.subscribe(()=>{if(this.scene3D){const u=this.params.desiredState.cameraRotation.getState();u?this.scene3D.startCameraRotation(u.x,u.y,u.z):this.scene3D.stopCameraRotation(!1)}}),this.textTracksManager.connect(this.video,t,e);const c=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(c,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=Ve(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,c=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),u=ht(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:c,current:i,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),l=e?u??s:s??u;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===w.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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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)}}};init3DScene=e=>{this.scene3D||(this.scene3D=new La(this.params.container,this.video,e),this.scene3D.play())};destroy3DScene=()=>{this.scene3D&&this.scene3D.destroy(()=>{this.scene3D=null})};destroy(){this.subscription.unsubscribe(),this.destroy3DScene(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Fa=5e3,Ee={};var L;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(L||(L={}));const yt=(r,e)=>new a.Observable(t=>{const s=(i,n)=>t.next(n);return r.on(e,s),()=>r.off(e,s)});class Ua{subscription=new a.Subscription;videoState=new j(L.INITIALIZING);video;params;hls;textTracksManager=new be;trackLevels=new Map;constructor(e){this.video=Pe(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.video.remove(),this.params.output.element$.next(void 0)}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"),Fa);import("hls.js/dist/hls.min.js").then(i=>{e||(Ee.Hls=i.default,Ee.Events=i.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(Ee.Hls,"hls.js not loaded"),this.hls=new Ee.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(L.STOPPED)}subscribe(){a.assertNonNullable(Ee.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},i=we(this.video),n=(u,l)=>this.subscription.add(u.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$),this.subscription.add(He(this.video,e.isLooped,s)),this.subscription.add(Ae(this.video,e.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,i.playbackRateState$,s)),this.subscription.add(yt(this.hls,Ee.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(L.PLAYING),T(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED),T(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===L.READY&&this.videoState.setState(L.READY),this.videoState.getState()===L.PLAYING&&this.playIfAllowed()},s)),n(yt(this.hls,Ee.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((l,h)=>{const p=h.name||h.height.toString(10),{width:S,height:f}=h,m=pt(h.attrs.QUALITY??"")??Ue({width:S,height:f});if(!m)return l;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,k={id:p.toString(),quality:m,bitrate:h.bitrate/1e3,size:{width:S,height:f},fps:g};return this.trackLevels.set(p,{track:k,level:h}),l.push(k),l},[]))),t.availableVideoTracks$),n(yt(this.hls,Ee.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ae(u))),t.hostname$),this.subscription.add(Se(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:s}));const o=u=>Array.from(this.trackLevels.values()).find(({level:l})=>l===u)?.track,c=yt(this.hls,Ee.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));c.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Se(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel])?.id,u=>{if(a.isNullable(u))return;const l=this.trackLevels.get(u)?.level;if(!l)return;const h=this.hls.levels.indexOf(l),p=this.hls.currentLevel,S=this.hls.levels[p];!S||l.bitrate>S.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:c.pipe(a.map(u=>u?.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!==L.INITIALIZING)switch(s?.to!==exports.PlaybackState.PAUSED&&i.state===w.Requested&&this.seek(i.position),t){case exports.PlaybackState.STOPPED:switch(e){case L.STOPPED:break;case L.READY:case L.PLAYING:case L.PAUSED:this.stop();break;default:a.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case L.STOPPED:this.prepare();break;case L.READY:case L.PLAYING:case L.PAUSED:break;default:a.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case L.PLAYING:break;case L.STOPPED:this.prepare();break;case L.READY:case L.PAUSED:this.playIfAllowed();break;default:a.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case L.PAUSED:break;case L.STOPPED:this.prepare();break;case L.READY:this.videoState.setState(L.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case L.PLAYING:this.pause();break;default:a.assertNever(e)}break;default:a.assertNever(t)}};prepare(){this.videoState.startTransitionTo(L.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(L.PLAYING),await xe(this.video)||(this.videoState.setState(L.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(L.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(L.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const ts="X-Playback-Duration";var ss=async r=>{const e=await We(r,{method:"HEAD"});return e.headers.has(ts)?parseInt(e.headers.get(ts),10):void 0};const Ha=r=>{let e=null;if(r.QUALITY&&(e=pt(r.QUALITY)),!e&&r.RESOLUTION){const[t,s]=r.RESOLUTION.split("x").map(i=>parseInt(i,10));e=Ue({width:t,height:s})}return e??null},_s=async(r,e=r)=>{const i=(await(await We(r)).text()).split(`
|
|
66
|
+
`),n=[];for(let o=0;o<i.length;o++){const d=i[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const u=Object.fromEntries(d[1].split(",").map(g=>g.split("="))),l=u.QUALITY??`stream-${u.BANDWIDTH}`,h=Ha(u);let p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const S=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let f;if(u.RESOLUTION){const[g,k]=u.RESOLUTION.split("x").map(P=>parseInt(P,10));g&&k&&(f={width:g,height:k})}const m=new URL(i[++o],e).toString();h&&n.push({id:l,quality:h,url:m,bandwidth:p,size:f,fps:S})}return n};var F;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(F||(F={}));class Ya{subscription=new a.Subscription;videoState=new j(F.STOPPED);video;params;textTracksManager=new be;manifests$=new a.ValueSubject([]);maxSeekBackTime$;liveOffset=new Ot;manifestStartTime$=new a.ValueSubject(void 0);constructor(e){this.params=e,this.video=Pe(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]),_s(Qe(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 c=s?"master":n;return s&&!i&&t.startTransitionTo("master"),o.find(d=>d.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=c=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:c})},i=we(this.video),n=(c,d)=>this.subscription.add(c.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$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ie(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(F.PLAYING),T(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED),T(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===F.READY&&this.videoState.setState(F.READY),this.videoState.getState()===F.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(c=>-c/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const p=this.manifests$.getValue().find(S=>S.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ae(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===F.CHANGING_MANIFEST&&this.videoState.setState(d.to),c&&c.state===w.Requested&&this.seek(c.position)},s)),this.subscription.add(i.loadedData$.subscribe(()=>{const c=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(c||void 0)},s)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:c,currentTime:d})=>this.params.output.liveTime$.next(c+d*1e3),s)),this.subscription.add(this.manifests$.pipe(a.map(c=>c.map(({id:d,quality:u,size:l,bandwidth:h,fps:p})=>({id:d,quality:u,size:l,fps:p,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.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Qe(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),ss(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{We(t).then(n=>n.text()).then(n=>{const o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n)?.[1];if(o){const c=new URL(o,t).toString();ss(c).then(d=>{a.isNullable(d)||this.maxSeekBackTime$.next(d)})}})}catch{}}})}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState(F.PAUSED),this.liveOffset.pause(),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const 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!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(F.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(e===F.STOPPED){this.videoState.startTransitionTo(F.READY),this.prepare();return}if(i||n){const d=this.videoState.getState();this.videoState.setState(F.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),c.state===w.None&&this.params.desiredState.seekState.setState({state:w.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==exports.PlaybackState.PAUSED&&c.state===w.Requested){this.videoState.startTransitionTo(F.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case F.READY:t===exports.PlaybackState.READY?T(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(F.PAUSED),this.liveOffset.pause(),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed());return;case F.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(F.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&T(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case F.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(F.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 F.CHANGING_MANIFEST:break;default:return a.assertNever(e)}}}var q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(q||(q={}));class qa{subscription=new a.Subscription;videoState=new j(q.STOPPED);video;params;textTracksManager=new be;manifests$=new a.ValueSubject([]);constructor(e){this.params=e,this.video=Pe(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)),_s(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 c=s?"master":n;return s&&!i&&t.startTransitionTo("master"),o.find(d=>d.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=c=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:c})},i=we(this.video),n=(c,d)=>this.subscription.add(c.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$),this.subscription.add(He(this.video,t.isLooped,s)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ie(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),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),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},s).add(i.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const p=this.manifests$.getValue().find(S=>S.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ae(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===q.CHANGING_MANIFEST&&this.videoState.setState(d.to),c.state===w.Requested&&this.seek(c.position)},s))),this.subscription.add(this.manifests$.pipe(a.map(c=>c.map(({id:d,quality:u,size:l,bandwidth:h,fps:p})=>({id:d,quality:u,size:l,fps:p,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.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),T(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(e===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(i||n){const d=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:u}=this.video;this.prepare(),c.state===w.None&&this.params.desiredState.seekState.setState({state:w.Requested,position:u*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&c.state===w.Requested&&this.seek(c.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;case q.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 ja{subscription=new a.Subscription;videoState=new j(Q.STOPPED);video;trackUrls={};params;textTracksManager=new be;constructor(e){this.params=e,this.video=Pe(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=c=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:c})},i=we(this.video),n=(c,d)=>this.subscription.add(c.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$),this.subscription.add(He(this.video,t.isLooped,s)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ie(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 c=this.params.desiredState.videoTrack.getTransition();c&&a.isNonNullable(c.to)&&(this.params.desiredState.videoTrack.setState(c.to),this.params.output.currentVideoTrack$.next(this.trackUrls[c.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.video.remove(),this.params.output.element$.next(void 0)}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=Je(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ae(t))}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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:c}=this.video;this.prepare(),o.state===w.None&&this.params.desiredState.seekState.setState({state:w.Requested,position:c*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&o.state===w.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 is=["stun:videostun.mycdn.me:80"],Ga=1e3,za=3,xt=()=>null;class Qa{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=xt;externalStopCallback=xt;externalErrorCallback=xt;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:is}]};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),Ga)}normalizeOptions(e={}){const t={stunServerList:is,maxRetryNumber:za,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var U;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(U||(U={}));class Wa{subscription;params;log;video;videoState=new j(U.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=Pe(e.container),this.liveStreamClient=new Qa(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState: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:c})=>{this.log({message:`[videoState change] ${c}: ${JSON.stringify(o)}`})});const i=we(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,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===U.READY&&this.videoState.setState(U.READY)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED)},s)).add(i.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING)},s)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ae(this.video,t.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case U.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case U.READY:break;case U.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case U.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(U.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(){xe(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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!==U.STOPPED&&(this.videoState.startTransitionTo(U.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(U.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===U.STOPPED){this.videoState.startTransitionTo(U.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case U.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),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.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.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&T(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(e)}}}class as{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 Ja=()=>{const r=window.navigator;return r.userAgentData?r.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const Cs=Ja(),Dt=document.createElement("video"),ve={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Dt.canPlayType?.("application/x-mpegurl")||Dt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},ne={mp4:Boolean(Dt.canPlayType?.("video/mp4")),webm:Boolean(Dt.canPlayType?.("video/webm")),cmaf:!0},Ne={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"'))},je=(Ne.h264||Ne.h265)&&Ne.aac,Nt=ve.hls&&ne.mp4,Xa=Boolean(window.WebSocket),Ka=()=>Object.keys(Ne).filter(r=>Ne[r]),Za=(r,e=!1)=>r.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ve.mse&&ne.mp4&&je;case exports.VideoFormat.DASH_SEP:return ve.mse&&ne.mp4&&je;case exports.VideoFormat.DASH_WEBM:return ve.mse&&ne.webm&&Ne.vp9&&Ne.opus;case exports.VideoFormat.DASH_LIVE:return ve.mse&&ne.mp4&&je;case exports.VideoFormat.DASH_LIVE_CMAF:return ve.mse&&ne.mp4&&je&&ne.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return ve.mse&&ne.mp4&&je;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Nt||e&&ve.mse&&ne.mp4&&je;case exports.VideoFormat.MPEG:return ne.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ve.webrtc&&Xa&&Ne.h264&&(ne.mp4||ne.webm);default:return a.assertNever(t)}}),er=()=>Cs?[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]:Nt?[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],tr=()=>Cs?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Nt?[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],rs=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 sr=r=>new a.Observable(e=>{const t=new a.Subscription,s=r.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:l})=>`${u}-${l}`)),i=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$,o=new a.Subject;let c=0,d="unknown";return t.add(s.subscribe(u=>{c&&window.clearTimeout(c),d=u,c=window.setTimeout(()=>o.next(u),r.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(c),d="provider change",c=0})),t.add(n.subscribe(()=>{c&&(window.clearTimeout(c),c=window.setTimeout(()=>o.next(d),r.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const ns={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},ir={cacheDuration:12e4},ar={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},rr={maxPausedTime:3e4},os={maxPausedTime:3e4};class nr{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),element$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)};subscription=new a.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Za([...tr(),...er()],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 as(i);const n=[...rs(!0),...rs(!1)];this.chromecastFormatsIterator=new as(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!==w.None;this.params.desiredState.seekState.setState({state:w.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 c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),new Gi({...o,source:c,config:ir})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),this.params.tuning.useDashJs?new zt({...o,source:c,format:e,config:os}):new Oa({...o,source:c})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),new zt({...o,source:c,format:e,config:os})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),Nt||!this.params.tuning.useHlsJs?new qa({...o,source:c}):new Ua({...o,source:c})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),new Ya({...o,source:c,config:rr})}case exports.VideoFormat.MPEG:{const c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),new ja({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),new Ui({...o,source:c,config:ar})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return a.assertNonNullable(c),new Wa({container:s,source:c,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,c=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(c),new ri({connection:c,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$,sr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:ns.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),c=s<ns.providerErrorLimit;o&&(n&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(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 Ns=new Map;let Fe=de.RUNTIME;const Lt=`vk-videoplayer-dummy-key-${Math.random()}`,or=()=>{try{localStorage.setItem(Lt,"test"),localStorage.removeItem(Lt),Fe=de.LOCAL_STORAGE}catch(r){if(r instanceof DOMException||r instanceof TypeError)try{sessionStorage.getItem(Lt),Fe=de.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Fe=de.RUNTIME;else throw e}else throw r}};or();const cr=r=>{switch(Fe){case de.LOCAL_STORAGE:return localStorage.getItem(r)??void 0;case de.SESSION_STORAGE:return sessionStorage.getItem(r)??void 0;case de.RUNTIME:return Ns.get(r);default:a.assertNever(Fe)}},cs=(r,e)=>{switch(Fe){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 Ns.set(r,e);default:a.assertNever(Fe)}},Vt=(r,e,t)=>t*e+(1-t)*r,Is=(r,e)=>r.reduce((t,s)=>t+s,0)/e,ur=(r,e,t,s)=>{let i=0,n=t;const o=Is(r,e),c=e<s?e:s;for(let d=0;d<c;d++)r[n]>o?i++:i--,n=(r.length+n-1)%r.length;return Math.abs(i)===c};class xs{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 c=0;c<this.pastMeasures.length;c++)this.pastMeasures[c]!==void 0&&(t+=(this.pastMeasures[c]-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 dr extends xs{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Vt(this.slow,e,this.params.emaAlphaSlow),this.fast=Vt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class lr extends xs{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Is(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Vt(this.emaSmoothed,e,this.params.emaAlpha);const s=ur(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class us{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new dr({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new lr({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const hr=5e3,ds="one_video_throughput",ls="one_video_rtt",dt=window.navigator.connection,hs=()=>{const r=dt?.downlink;if(a.isNonNullable(r)&&r!==10)return r*1e3},ps=()=>{const r=dt?.rtt;if(a.isNonNullable(r)&&r!==3e3)return r},fs=(r,e,t)=>{const s=t*8,i=s/r;return s/(i+e)};class lt{throughput;rtt;subscription=new a.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=lt.load(ds)||(e.useBrowserEstimation?hs():void 0)||hr,s=lt.load(ls)??(e.useBrowserEstimation?ps():void 0)??0;if(this.throughput$=new a.ValueSubject(t),this.rtt$=new a.ValueSubject(s),this.rttAdjustedThroughput$=new a.ValueSubject(fs(t,s,e.rttPenaltyRequestSize)),this.throughput=us.getSmoothedValue(t,-1,e),this.rtt=us.getSmoothedValue(s,1,e),e.useBrowserEstimation){const i=()=>{const o=hs();o&&this.throughput.next(o);const c=ps();a.isNonNullable(c)&&this.rtt.next(c)};dt&&"onchange"in dt&&this.subscription.add(a.fromEvent(dt,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{cs(ds,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{cs(ls,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})=>fs(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,c=a.now(),d=o-t,u=c-s;this.addRawSpeed(d,u,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 c=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:l})=>{u?(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,c))};this.concurrentDownloads.add(e),t?.read().then(d,c)}addRawSpeed(e,t,s=1){if(lt.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=cr(e);if(a.isNonNullable(t))return parseInt(t,10)??void 0}}const ms={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}},pr=r=>{const e={};for(const t of Object.keys(ms)){const s=ms[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 fr=({seekState:r,position$:e})=>a.merge(r.stateChangeEnded$.pipe(a.map(({to:t})=>t.state===w.None?void 0:(t.position??NaN)/1e3),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>r.getState().state===w.None))),mr=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return a.assertNonNullable(e,`Wrong container or containerId {${r.container}}`),e};const Ss=({playbackState:r,seekState:e,playbackAbort$:t,looped$:s,position$:i})=>new a.Observable(n=>{let o;const c=r.transitionEnded$.pipe(a.filter(S=>(S.from===exports.PlaybackState.PAUSED||S.from===exports.PlaybackState.STOPPED)&&S.to===exports.PlaybackState.PLAYING)),d=r.stateChangeEnded$.pipe(a.filter(S=>S.from===exports.PlaybackState.PLAYING&&S.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:S})=>S.state===w.Requested&&(r.getTransition()?.from??r.getState())===exports.PlaybackState.PLAYING)),l=e.stateChangeEnded$.pipe(a.filter(({from:S,to:f})=>S.state===w.Applying&&f.state===w.None&&(r.getTransition()?.from??r.getState())===exports.PlaybackState.PLAYING)),h=a.merge(c,l).pipe(a.map(()=>i.getValue()),a.filter(a.isNonNullable)),p=a.merge(a.merge(d,u,t),s).pipe(a.map(()=>i.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(S=>{o=S})).add(p.subscribe(S=>{if(a.isNullable(o)||o===S)return;const f={from:o,to:S};o=void 0,n.next(f)}))});class Sr{subscription=new a.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new a.Logger;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new j(exports.PlaybackState.STOPPED),seekState:new j({state:w.None}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),autoVideoTrackSwitching:new j(!1),autoVideoTrackLimits:new j({}),isLooped:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraRotation:new j(!1)};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),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),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)};events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$: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:Ti};constructor(e={}){if(this.initLogs(),this.tuning=pr(e),this.chromecastInitializer=new Qs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new lt(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(c){const d=o.map(h=>JSON.stringify(h,(p,S)=>{const f=typeof S;return["number","string","boolean"].includes(f)?S:S===null?null:`<${f}>`})),u=`Player.${String(s)}`,l=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:l,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.domContainer=mr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new nr({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:w.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()}startCameraRotation(e,t){return this.desiredState.cameraRotation.setState({x:e,y:t,z:0}),this}stopCameraRotation(){return this.desiredState.cameraRotation.setState(!1),this}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===w.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$.pipe(a.filter(()=>!this.isPlaybackStarted),a.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===w.Requested?this.desiredState.seekState.setState({...d,state:w.Applying}):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===w.Applying&&(this.desiredState.seekState.setState({state:w.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,l)=>vt(u)?1:vt(l)?-1:Tt(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const l of d)l.fps&&(u[l.quality]=l.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(d=>{this.info.currentQuality$.next(d?.quality),this.info.videoBitrate$.next(d?.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(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(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(fr({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(d=>({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(()=>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:d})=>d===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 d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||s.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const c=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d?.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>u.next(l&&Math.floor(l/1e3)))),o.add(Ss({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:c,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:l,to:h})=>({start:l,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(Ss({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:c,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:l})=>({start:u,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(a.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 u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d?.size?.width,height:d?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(d=>{this.info.is3DVideo$.next(d)}))}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=ht(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),yi(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>gi(t)),this.providerContainer.current$.subscribe(({type:t})=>St("provider",t)),e.duration$.subscribe(t=>St("duration",t)),e.availableVideoTracks$.pipe(a.filter(t=>!!t.length),a.once()).subscribe(t=>St("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)),St("codecs",Ka())}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=>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 br=`${Gs}@${js}`;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=Sr;exports.SDK_VERSION=br;
|