@vkontakte/videoplayer-core 2.0.95 → 2.0.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- package/package.json +1 -1
package/esnext.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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.96
|
|
3
|
+
* Wed, 13 Dec 2023 12:11:59 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-96/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Wi=Object.create;var Xt=Object.defineProperty;var Ji=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var Ki=Object.getPrototypeOf,Zi=Object.prototype.hasOwnProperty;var es=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Xi(e))!Zi.call(r,a)&&a!==t&&Xt(r,a,{get:()=>e[a],enumerable:!(i=Ji(e,a))||i.enumerable});return r};var Kt=(r,e,t)=>(t=r!=null?Wi(Ki(r)):{},es(e||!r||!r.__esModule?Xt(t,"default",{value:r,enumerable:!0}):t,r));var s=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),ts=require("lodash/debounce.js");const Ai="2.0.95";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_AV1="DASH_WEBM_AV1",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 ie;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(ie||(ie={}));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 R;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(R||(R={}));exports.Surface=void 0;(function(r){r.NONE="none",r.INLINE="inline",r.FULLSCREEN="fullscreen",r.SECOND_SCREEN="second_screen",r.PIP="pip"})(exports.Surface||(exports.Surface={}));var is=r=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class ss{connection$=new s.ValueSubject(void 0);castState$=new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new s.Subject;contentId;realCastState$=new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new s.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 i=s.isNonNullable(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||is("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:s.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(){s.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();s.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();s.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),i=cast.framework.CastContext.getInstance();this.subscription.add(s.fromEvent(i,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=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return s.assertNever(a.sessionState)}})).add(s.merge(s.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(s.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),s.map(a=>a.castState)),s.observableFrom([i.getCastState()])).pipe(s.filterChanged(),s.map(as),s.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{const n=a===exports.ChromecastState.CONNECTED,o=s.isNonNullable(this.connection$.getValue());if(n&&!o){const c=i.getCurrentSession();s.assertNonNullable(c);const d=c.getCastDevice(),u=c.getMediaSession()?.media.contentId;(s.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(a===exports.ChromecastState.CONNECTED?s.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:s.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const as=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 s.assertNever(r)}};var K;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",r[r.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(K||(K={}));var me=(r,e=0,t=K.OFFSET_P)=>{switch(t){case K.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case K.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case K.DASH_CMAF_OFFSET_P:{if(e===0)return r;const i=new URL(r);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:s.assertNever(t)}return r};const Zt=(r,e)=>{switch(e){case K.OFFSET_P:return NaN;case K.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case K.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:s.assertNever(e)}};var k=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class z{state;prevState;transition;transitionStarted$=new s.Subject;transitionEnded$=new s.Subject;transitionUpdated$=new s.Subject;forceChanged$=new s.Subject;stateChangeStarted$=s.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=s.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||s.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const rs=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.DASH_WEBM_AV1: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 s.assertNever(r)}};var _;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(_||(_={}));const ns=5,os=5,cs=500,ei=7e3;class us{subscription=new s.Subscription;loadMediaTimeoutSubscription=new s.Subscription;videoState=new z(_.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(rs(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 s.Subscription;this.subscription.add(e),this.subscription.add(s.merge(this.videoState.stateChangeStarted$.pipe(s.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(s.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 s.Subject;e.add(a.pipe(s.debounce(cs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(s.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===R.Applying||Math.abs(c-n)>ns)&&a.next(c),n=c})),e.add(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(s.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(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.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<os&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:s.assertNever(o)}}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=s.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));t(i,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),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(_.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:R.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===_.PAUSED||e===_.PLAYING)&&(this.videoState.setState(_.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===_.PLAYING||e===_.PAUSED)&&(this.videoState.setState(_.PLAYING),k(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&&k(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(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,a,n;switch(e){case exports.VideoFormat.MPEG:{const u=t[e];s.assertNonNullable(u);const h=s.getHighestQuality(Object.keys(u));s.assertNonNullable(h);const l=u[h];s.assertNonNullable(l),i=l,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=t[e];s.assertNonNullable(u),i=u.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:case exports.VideoFormat.DASH_WEBM_AV1:{const u=t[e];s.assertNonNullable(u),i=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=t[e];s.assertNonNullable(u),i=u.url,a="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];s.assertNonNullable(u),i=me(u.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 u="Unsupported format for Chromecast",h=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:s.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return s.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);o.contentUrl=i,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:d}=this.params.meta;return s.isNonNullable(c)&&(o.metadata.title=c),s.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===R.Applying||i.state===R.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((a,n)=>{this.loadMediaTimeoutSubscription.add(s.timeout(ei).subscribe(()=>n(`timeout(${ei})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===R.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:s.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(),i=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: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==_.STOPPED&&(this.videoState.startTransitionTo(_.STOPPED),this.stop());return}if(!t){if(a?.to!==exports.PlaybackState.PAUSED&&n.state===R.Requested&&e!==_.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case _.PLAYING:case _.PAUSED:case _.READY:break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:s.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:s.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:s.assertNever(e)}break}default:s.assertNever(i)}}}}var ds=r=>{let e,t=!1,i=!1;r.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&e?.()}),r.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&e?.()}}},!0)},ls=r=>{const e=new s.ValueSubject(1/0),t=new s.Subject,i=new s.ValueSubject(void 0),a=new s.ValueSubject(void 0);let n=NaN,o=!1;const c=()=>{n=Date.now(),o=!1},d=h=>{const l=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in l||"x-playback-duration-millis"in l){const S=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),g=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;s.isNonNullable(g)&&!isNaN(g)&&e.next(g)}const p=l["x-delivery-type"]??exports.HttpConnectionType.HTTP1,f={1:!0,0:!1}[l["x-reused"]]??void 0;i.next(p),a.next(f)},u=h=>{h.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return r.extend("XHRLoader",function(){const{parent:h}=this,l=h.load.bind(h);return{load:function(p){if(p.request.type==="MPD"){const f=p.onload,S=p.progress;p.onload=function(...y){return d(this),f(...y)},p.progress=function(...y){return u(this),S(...y)},c()}return l(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},Je=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},hs=r=>r.extend("RequestModifier",()=>({modifyRequestURL:Je}),!0),ps=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(c=>parseInt(c,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Se=(r,e,t,{equal:i=(o,c)=>o===c,changed$:a,onError:n}={})=>{const o=r.getState(),c=e(),d=s.isNullable(a),u=new s.Subscription;return a&&u.add(a.subscribe(h=>{const l=r.getState();i(h,l)&&r.setState(h)},n)),i(c,o)||(t(o),d&&r.setState(o)),u.add(r.stateChangeStarted$.subscribe(h=>{t(h.to),d&&r.setState(h.to)},n)),u},Ye=(r,e,t)=>Se(e,()=>r.loop,i=>{s.isNonNullable(i)&&(r.loop=i)},{onError:t}),Ce=(r,e,t,i)=>Se(e,()=>({muted:r.muted,volume:r.volume}),a=>{s.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:i}),Ve=(r,e,t,i)=>Se(e,()=>r.playbackRate,a=>{s.isNonNullable(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),fs=r=>["__",r.language,r.label].join("|"),ms=(r,e)=>{if(r.id===e)return!0;const[t,i,a]=e.split("|");return r.language===i&&r.label===a};class Ee{available$=new s.Subject;current$=new s.ValueSubject(void 0);error$=new s.Subject;video;cueSettings;subscription=new s.Subscription;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:s.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Se(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{s.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>s.isNonNullable(n)&&s.isNonNullable(o)&&n.length===o.length&&n.every(({id:c},d)=>c===o[d].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(Se(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{s.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>s.isNonNullable(n)&&s.isNonNullable(o)&&n.length===o.length&&n.every(({id:c},d)=>c===o[d].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),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:a})),this.subscription.add(Se(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){s.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(s.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(s.merge(s.fromEvent(e,"addtrack"),s.fromEvent(e,"removetrack"),s.observableFrom(["init"])).pipe(s.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),s.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(s.merge(s.fromEvent(e,"change"),s.observableFrom(["init"])).pipe(s.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),s.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),s.filterChanged()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(s.fromEvent(e,"addtrack").subscribe(i=>{i.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))};i.track?.addEventListener("cuechange",a)})),this.subscription.add(s.fromEvent(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;s.isNonNullable(t.align)&&(a.align=t.align),s.isNonNullable(t.position)&&(a.position=t.position),s.isNonNullable(t.size)&&(a.size=t.size),s.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){s.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ee.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id?e.id:fs(e),n=this.externalTracks.has(a),o=a.includes("auto");return n?{id:a,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===a&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){s.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(s.isNullable(e)||!ms(t,e))&&(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){s.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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){s.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const qt=r=>{r.removeAttribute("src"),r.load()},Ss=r=>{try{r.pause(),r.playbackRate=0,qt(r),r.remove()}catch(e){console.error(e)}};class bs{attribute="data-pool-reused";get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Ut=window.WeakMap?new WeakMap:new bs,_e=r=>{let e=r.querySelector("video");const t=!!e;return e?qt(e):(e=document.createElement("video"),r.appendChild(e)),Ut.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},xe=r=>{const e=Ut.get(r);Ut.delete(r),e?qt(r):Ss(r)};class xt{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Pi=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ti=r=>{const e=Pi(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},gs=r=>{const e=Pi(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},Ht=3;class ys{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Ht&&(a=e),this._buffer.push({from:a,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ht))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:a,to:n})=>{const o=a>=e&&a<t,c=n>=e&&n<t;o&&c||(o?i(t,n):c?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var wi=(r,e,t=Ht)=>{let i=0,a=0;for(let n=0;n<r.length;n++){const o=r.start(n),c=r.end(n);if(o<=e&&e<=c){if(i=o,a=c,!t)return{from:i,to:a};for(let d=n-1;d>=0;d--)r.end(d)+t>=i&&(i=r.start(d));for(let d=n+1;d<r.length;d++)r.start(d)-t<=a&&(a=r.end(d))}}return{from:i,to:a}};const Re=r=>{const e=m=>s.fromEvent(r,m).pipe(s.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=s.merge(...t.map(m=>s.fromEvent(r,m))).pipe(s.map(m=>m.type==="ended"?r.readyState<2:r.readyState<3),s.filterChanged()),a=s.merge(s.fromEvent(r,"progress"),s.fromEvent(r,"timeupdate")).pipe(s.map(()=>wi(r.buffered,r.currentTime))),o=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari?s.combine({play:e("play").pipe(s.once()),playing:e("playing")}).pipe(s.mapTo(void 0)):e("playing"),c=s.fromEvent(r,"volumechange").pipe(s.map(()=>({muted:r.muted,volume:r.volume}))),d=s.fromEvent(r,"ratechange").pipe(s.map(()=>r.playbackRate)),u=s.fromEvent(r,"error").pipe(s.filter(()=>!!(r.error||r.played.length)),s.map(()=>{const m=r.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:s.ErrorCategory.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:r.error??void 0}})),h=s.fromEvent(r,"timeupdate").pipe(s.map(()=>r.currentTime)),l=new s.Subject,p=.3;let f;h.subscribe(m=>{r.loop&&s.isNonNullable(f)&&s.isNonNullable(m)&&f>=r.duration-p&&m<=p&&l.next(f),f=m});const S=s.fromEvent(r,"enterpictureinpicture"),y=s.fromEvent(r,"leavepictureinpicture"),g=new s.ValueSubject(gs(r));S.subscribe(()=>g.next(!0)),y.subscribe(()=>g.next(!1));const A=new s.ValueSubject(ti(r));return s.fromEvent(r,"fullscreenchange").pipe(s.map(()=>ti(r))).subscribe(A),{playing$:o,pause$:e("pause").pipe(s.filter(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:s.fromEvent(r,"durationchange").pipe(s.map(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:c,playbackRateState$:d,inPiP$:g,inFullscreen$:A}},zt=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let Qt=!1,we={};const Ts=r=>{Qt=r},vs=()=>{we={}},Es=r=>{r(we)},Tt=(r,e)=>{Qt&&(we.meta=we.meta??{},we.meta[r]=e)};class ye{name;constructor(e){this.name=e}next(e){if(!Qt)return;we.series=we.series??{};const t=we.series[this.name]??[];t.push([Date.now(),e]),we.series[this.name]=t}}var He;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(He||(He={}));const ks=new ye("best_bitrate"),$s=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class As{last;history={};recordSelection(e){this.history[e.id]=s.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Ze=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:d,history:u,droppedVideoMaxQualityLimit:h,abrLogger:l})=>{const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},S=f&&s.videoSizeToQuality(f),y=i.considerPlaybackRate&&s.isNonNullable(c)?c:1,g=r.filter(E=>!s.isInvariantQuality(E.quality)).sort((E,C)=>s.isHigher(E.quality,C.quality)?-1:1),A=g.at(-1)?.quality,w=g.at(0)?.quality,m=s.isNullable(a)||s.isNonNullable(a.min)&&s.isNonNullable(a.max)&&s.isLower(a.max,a.min)||s.isNonNullable(a.min)&&w&&s.isHigher(a.min,w)||s.isNonNullable(a.max)&&A&&s.isLower(a.max,A),T=y*$s(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),v={},V=g.filter(E=>(S?s.isLower(E.quality,S):!0)?(s.isNonNullable(t)&&isFinite(t)&&s.isNonNullable(E.bitrate)?t-n>=E.bitrate*T:!0)?i.lazyQualitySwitch&&s.isNonNullable(i.minBufferToSwitchUp)&&d&&!s.isInvariantQuality(d.quality)&&(o??0)<i.minBufferToSwitchUp&&s.isHigher(E.quality,d.quality)?(v[E.quality]=He.Buffer,!1):!!h&&s.isHigherOrEqual(E.quality,h)?(v[E.quality]=He.DroppedFramesLimit,!1):m||(s.isNullable(a.max)||s.isLowerOrEqual(E.quality,a.max))&&(s.isNullable(a.min)||s.isHigherOrEqual(E.quality,a.min))?!0:(v[E.quality]=He.FitsQualityLimits,!1):(v[E.quality]=He.FitsThroughput,!1):(v[E.quality]=He.FitsContainer,!1))[0];V&&V.bitrate&&ks.next(V.bitrate);const L=V??g[Math.ceil((g.length-1)/2)]??r[0];L.quality!==u?.last?.quality&&l({message:`
|
|
6
|
+
"use strict";var Wi=Object.create;var Xt=Object.defineProperty;var Ji=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var Ki=Object.getPrototypeOf,Zi=Object.prototype.hasOwnProperty;var es=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Xi(e))!Zi.call(r,a)&&a!==t&&Xt(r,a,{get:()=>e[a],enumerable:!(i=Ji(e,a))||i.enumerable});return r};var Kt=(r,e,t)=>(t=r!=null?Wi(Ki(r)):{},es(e||!r||!r.__esModule?Xt(t,"default",{value:r,enumerable:!0}):t,r));var s=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),ts=require("lodash/debounce.js");const Ai="2.0.96";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_AV1="DASH_WEBM_AV1",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 ie;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(ie||(ie={}));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 R;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(R||(R={}));exports.Surface=void 0;(function(r){r.NONE="none",r.INLINE="inline",r.FULLSCREEN="fullscreen",r.SECOND_SCREEN="second_screen",r.PIP="pip"})(exports.Surface||(exports.Surface={}));var is=r=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class ss{connection$=new s.ValueSubject(void 0);castState$=new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new s.Subject;contentId;realCastState$=new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new s.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 i=s.isNonNullable(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||is("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:s.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(){s.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();s.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();s.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),i=cast.framework.CastContext.getInstance();this.subscription.add(s.fromEvent(i,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=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return s.assertNever(a.sessionState)}})).add(s.merge(s.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(s.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),s.map(a=>a.castState)),s.observableFrom([i.getCastState()])).pipe(s.filterChanged(),s.map(as),s.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{const n=a===exports.ChromecastState.CONNECTED,o=s.isNonNullable(this.connection$.getValue());if(n&&!o){const c=i.getCurrentSession();s.assertNonNullable(c);const d=c.getCastDevice(),u=c.getMediaSession()?.media.contentId;(s.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(a===exports.ChromecastState.CONNECTED?s.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:s.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const as=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 s.assertNever(r)}};var K;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",r[r.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(K||(K={}));var me=(r,e=0,t=K.OFFSET_P)=>{switch(t){case K.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case K.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case K.DASH_CMAF_OFFSET_P:{if(e===0)return r;const i=new URL(r);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:s.assertNever(t)}return r};const Zt=(r,e)=>{switch(e){case K.OFFSET_P:return NaN;case K.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case K.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:s.assertNever(e)}};var k=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class z{state;prevState;transition;transitionStarted$=new s.Subject;transitionEnded$=new s.Subject;transitionUpdated$=new s.Subject;forceChanged$=new s.Subject;stateChangeStarted$=s.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=s.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||s.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const rs=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.DASH_WEBM_AV1: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 s.assertNever(r)}};var _;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(_||(_={}));const ns=5,os=5,cs=500,ei=7e3;class us{subscription=new s.Subscription;loadMediaTimeoutSubscription=new s.Subscription;videoState=new z(_.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(rs(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 s.Subscription;this.subscription.add(e),this.subscription.add(s.merge(this.videoState.stateChangeStarted$.pipe(s.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(s.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 s.Subject;e.add(a.pipe(s.debounce(cs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(s.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===R.Applying||Math.abs(c-n)>ns)&&a.next(c),n=c})),e.add(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(s.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(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.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<os&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:s.assertNever(o)}}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=s.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));t(i,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),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(_.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:R.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===_.PAUSED||e===_.PLAYING)&&(this.videoState.setState(_.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===_.PLAYING||e===_.PAUSED)&&(this.videoState.setState(_.PLAYING),k(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&&k(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(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,a,n;switch(e){case exports.VideoFormat.MPEG:{const u=t[e];s.assertNonNullable(u);const h=s.getHighestQuality(Object.keys(u));s.assertNonNullable(h);const l=u[h];s.assertNonNullable(l),i=l,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=t[e];s.assertNonNullable(u),i=u.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:case exports.VideoFormat.DASH_WEBM_AV1:{const u=t[e];s.assertNonNullable(u),i=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=t[e];s.assertNonNullable(u),i=u.url,a="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];s.assertNonNullable(u),i=me(u.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 u="Unsupported format for Chromecast",h=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:s.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return s.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);o.contentUrl=i,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:d}=this.params.meta;return s.isNonNullable(c)&&(o.metadata.title=c),s.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===R.Applying||i.state===R.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((a,n)=>{this.loadMediaTimeoutSubscription.add(s.timeout(ei).subscribe(()=>n(`timeout(${ei})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===R.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:s.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(),i=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: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==_.STOPPED&&(this.videoState.startTransitionTo(_.STOPPED),this.stop());return}if(!t){if(a?.to!==exports.PlaybackState.PAUSED&&n.state===R.Requested&&e!==_.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case _.PLAYING:case _.PAUSED:case _.READY:break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:s.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:s.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:s.assertNever(e)}break}default:s.assertNever(i)}}}}var ds=r=>{let e,t=!1,i=!1;r.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&e?.()}),r.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&e?.()}}},!0)},ls=r=>{const e=new s.ValueSubject(1/0),t=new s.Subject,i=new s.ValueSubject(void 0),a=new s.ValueSubject(void 0);let n=NaN,o=!1;const c=()=>{n=Date.now(),o=!1},d=h=>{const l=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in l||"x-playback-duration-millis"in l){const S=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),g=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;s.isNonNullable(g)&&!isNaN(g)&&e.next(g)}const p=l["x-delivery-type"]??exports.HttpConnectionType.HTTP1,f={1:!0,0:!1}[l["x-reused"]]??void 0;i.next(p),a.next(f)},u=h=>{h.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return r.extend("XHRLoader",function(){const{parent:h}=this,l=h.load.bind(h);return{load:function(p){if(p.request.type==="MPD"){const f=p.onload,S=p.progress;p.onload=function(...y){return d(this),f(...y)},p.progress=function(...y){return u(this),S(...y)},c()}return l(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},Je=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},hs=r=>r.extend("RequestModifier",()=>({modifyRequestURL:Je}),!0),ps=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(c=>parseInt(c,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Se=(r,e,t,{equal:i=(o,c)=>o===c,changed$:a,onError:n}={})=>{const o=r.getState(),c=e(),d=s.isNullable(a),u=new s.Subscription;return a&&u.add(a.subscribe(h=>{const l=r.getState();i(h,l)&&r.setState(h)},n)),i(c,o)||(t(o),d&&r.setState(o)),u.add(r.stateChangeStarted$.subscribe(h=>{t(h.to),d&&r.setState(h.to)},n)),u},Ye=(r,e,t)=>Se(e,()=>r.loop,i=>{s.isNonNullable(i)&&(r.loop=i)},{onError:t}),Ce=(r,e,t,i)=>Se(e,()=>({muted:r.muted,volume:r.volume}),a=>{s.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:i}),Ve=(r,e,t,i)=>Se(e,()=>r.playbackRate,a=>{s.isNonNullable(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),fs=r=>["__",r.language,r.label].join("|"),ms=(r,e)=>{if(r.id===e)return!0;const[t,i,a]=e.split("|");return r.language===i&&r.label===a};class Ee{available$=new s.Subject;current$=new s.ValueSubject(void 0);error$=new s.Subject;video;cueSettings;subscription=new s.Subscription;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:s.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Se(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{s.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>s.isNonNullable(n)&&s.isNonNullable(o)&&n.length===o.length&&n.every(({id:c},d)=>c===o[d].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(Se(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{s.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>s.isNonNullable(n)&&s.isNonNullable(o)&&n.length===o.length&&n.every(({id:c},d)=>c===o[d].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),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:a})),this.subscription.add(Se(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){s.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(s.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(s.merge(s.fromEvent(e,"addtrack"),s.fromEvent(e,"removetrack"),s.observableFrom(["init"])).pipe(s.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),s.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(s.merge(s.fromEvent(e,"change"),s.observableFrom(["init"])).pipe(s.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),s.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),s.filterChanged()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(s.fromEvent(e,"addtrack").subscribe(i=>{i.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))};i.track?.addEventListener("cuechange",a)})),this.subscription.add(s.fromEvent(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;s.isNonNullable(t.align)&&(a.align=t.align),s.isNonNullable(t.position)&&(a.position=t.position),s.isNonNullable(t.size)&&(a.size=t.size),s.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){s.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ee.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id?e.id:fs(e),n=this.externalTracks.has(a),o=a.includes("auto");return n?{id:a,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===a&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){s.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(s.isNullable(e)||!ms(t,e))&&(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){s.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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){s.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const qt=r=>{r.removeAttribute("src"),r.load()},Ss=r=>{try{r.pause(),r.playbackRate=0,qt(r),r.remove()}catch(e){console.error(e)}};class bs{attribute="data-pool-reused";get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Ut=window.WeakMap?new WeakMap:new bs,_e=r=>{let e=r.querySelector("video");const t=!!e;return e?qt(e):(e=document.createElement("video"),r.appendChild(e)),Ut.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},xe=r=>{const e=Ut.get(r);Ut.delete(r),e?qt(r):Ss(r)};class xt{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Pi=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ti=r=>{const e=Pi(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},gs=r=>{const e=Pi(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},Ht=3;class ys{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Ht&&(a=e),this._buffer.push({from:a,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ht))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:a,to:n})=>{const o=a>=e&&a<t,c=n>=e&&n<t;o&&c||(o?i(t,n):c?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var wi=(r,e,t=Ht)=>{let i=0,a=0;for(let n=0;n<r.length;n++){const o=r.start(n),c=r.end(n);if(o<=e&&e<=c){if(i=o,a=c,!t)return{from:i,to:a};for(let d=n-1;d>=0;d--)r.end(d)+t>=i&&(i=r.start(d));for(let d=n+1;d<r.length;d++)r.start(d)-t<=a&&(a=r.end(d))}}return{from:i,to:a}};const Re=r=>{const e=m=>s.fromEvent(r,m).pipe(s.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=s.merge(...t.map(m=>s.fromEvent(r,m))).pipe(s.map(m=>m.type==="ended"?r.readyState<2:r.readyState<3),s.filterChanged()),a=s.merge(s.fromEvent(r,"progress"),s.fromEvent(r,"timeupdate")).pipe(s.map(()=>wi(r.buffered,r.currentTime))),o=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari?s.combine({play:e("play").pipe(s.once()),playing:e("playing")}).pipe(s.mapTo(void 0)):e("playing"),c=s.fromEvent(r,"volumechange").pipe(s.map(()=>({muted:r.muted,volume:r.volume}))),d=s.fromEvent(r,"ratechange").pipe(s.map(()=>r.playbackRate)),u=s.fromEvent(r,"error").pipe(s.filter(()=>!!(r.error||r.played.length)),s.map(()=>{const m=r.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:s.ErrorCategory.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:r.error??void 0}})),h=s.fromEvent(r,"timeupdate").pipe(s.map(()=>r.currentTime)),l=new s.Subject,p=.3;let f;h.subscribe(m=>{r.loop&&s.isNonNullable(f)&&s.isNonNullable(m)&&f>=r.duration-p&&m<=p&&l.next(f),f=m});const S=s.fromEvent(r,"enterpictureinpicture"),y=s.fromEvent(r,"leavepictureinpicture"),g=new s.ValueSubject(gs(r));S.subscribe(()=>g.next(!0)),y.subscribe(()=>g.next(!1));const A=new s.ValueSubject(ti(r));return s.fromEvent(r,"fullscreenchange").pipe(s.map(()=>ti(r))).subscribe(A),{playing$:o,pause$:e("pause").pipe(s.filter(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:s.fromEvent(r,"durationchange").pipe(s.map(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:c,playbackRateState$:d,inPiP$:g,inFullscreen$:A}},zt=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let Qt=!1,we={};const Ts=r=>{Qt=r},vs=()=>{we={}},Es=r=>{r(we)},Tt=(r,e)=>{Qt&&(we.meta=we.meta??{},we.meta[r]=e)};class ye{name;constructor(e){this.name=e}next(e){if(!Qt)return;we.series=we.series??{};const t=we.series[this.name]??[];t.push([Date.now(),e]),we.series[this.name]=t}}var He;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(He||(He={}));const ks=new ye("best_bitrate"),$s=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class As{last;history={};recordSelection(e){this.history[e.id]=s.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Ze=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:d,history:u,droppedVideoMaxQualityLimit:h,abrLogger:l})=>{const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},S=f&&s.videoSizeToQuality(f),y=i.considerPlaybackRate&&s.isNonNullable(c)?c:1,g=r.filter(E=>!s.isInvariantQuality(E.quality)).sort((E,C)=>s.isHigher(E.quality,C.quality)?-1:1),A=g.at(-1)?.quality,w=g.at(0)?.quality,m=s.isNullable(a)||s.isNonNullable(a.min)&&s.isNonNullable(a.max)&&s.isLower(a.max,a.min)||s.isNonNullable(a.min)&&w&&s.isHigher(a.min,w)||s.isNonNullable(a.max)&&A&&s.isLower(a.max,A),T=y*$s(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),v={},V=g.filter(E=>(S?s.isLower(E.quality,S):!0)?(s.isNonNullable(t)&&isFinite(t)&&s.isNonNullable(E.bitrate)?t-n>=E.bitrate*T:!0)?i.lazyQualitySwitch&&s.isNonNullable(i.minBufferToSwitchUp)&&d&&!s.isInvariantQuality(d.quality)&&(o??0)<i.minBufferToSwitchUp&&s.isHigher(E.quality,d.quality)?(v[E.quality]=He.Buffer,!1):!!h&&s.isHigherOrEqual(E.quality,h)?(v[E.quality]=He.DroppedFramesLimit,!1):m||(s.isNullable(a.max)||s.isLowerOrEqual(E.quality,a.max))&&(s.isNullable(a.min)||s.isHigherOrEqual(E.quality,a.min))?!0:(v[E.quality]=He.FitsQualityLimits,!1):(v[E.quality]=He.FitsThroughput,!1):(v[E.quality]=He.FitsContainer,!1))[0];V&&V.bitrate&&ks.next(V.bitrate);const L=V??g[Math.ceil((g.length-1)/2)]??r[0];L.quality!==u?.last?.quality&&l({message:`
|
|
7
7
|
[available tracks] ${r.map(E=>E.quality).join(", ")}
|
|
8
8
|
|
|
9
9
|
[limit params]
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
[selected track] ${L.quality}
|
|
27
27
|
`});const M=L&&u&&u.history[L.id]&&s.now()-u.history[L.id]<=i.trackCooldown&&(!u.last||L.id!==u.last.id);if(L?.id&&u&&!M&&u.recordSelection(L),M&&u?.last){const E=u.last;return u?.recordSwitch(E),l({message:`
|
|
28
28
|
[last selected] ${E.quality}
|
|
29
|
-
`}),E}return u?.recordSwitch(L),L};var ne=r=>new URL(r).hostname;const Ps=300,At=(r,e=Ps)=>new s.Observable(t=>{const{width:i,height:a}=r.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(ts(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),s.isNonNullable(d)&&s.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(r),()=>n.disconnect()});class Rt{onDroopedVideoFramesLimit$=new s.Subject;subscription=new s.Subscription;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new s.Subject;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(s.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=s.interval(this.droppedFramesChecker.checkTime).pipe(s.filter(()=>this.playing),s.filter(()=>{const a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(s.debounce(this.droppedFramesChecker.checkTime)),i=s.merge(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!s.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,n=1-(i-a)/i;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&s.isHigher(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)};onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){const t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>s.isLower(i,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const rt={};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 X=(r,e)=>new s.Observable(t=>{const i=a=>t.next(a);return r.on(e,i),()=>r.off(e,i)});class ii{subscription=new s.Subscription;videoState=new z(N.DOWNLOADING_LIB);video;player;params;textTracksManager=new Ee;droppedFramesManager=new Rt;videoTracks$=new s.ValueSubject([]);frameRatesByFrameHeight={};isLive$=new s.ValueSubject(void 0);maxSeekBackTime$=new s.ValueSubject(1/0);availableFrom$=new s.ValueSubject(void 0);elementSize$=new s.ValueSubject(void 0);liveOffset=new xt;constructor(e){this.video=_e(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(ne(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:s.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${a?.toString?.()}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(rt.MediaPlayer=a.MediaPlayer,rt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(rt.MediaPlayer,"dashjs not loaded"),s.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(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?zt(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&ps(this.player),ds(this.player),this.params.tuning.requestQuick&&hs(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(N.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:s.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},a=(m,T)=>this.subscription.add(m.subscribe(T,i));a(At(this.video),this.elementSize$),a(X(this.player,"error").pipe(s.map(m=>{const T=typeof m.error=="object"?m.error.code:m.error,v=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${T}`,message:v}})),e.error$),a(X(this.player,"playbackError").pipe(s.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=X(this.player,"qualityChangeRendered").pipe(s.filter(({mediaType:m})=>m==="video"),s.map(({newQuality:m})=>this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===m)?.track));n.pipe(s.filter(s.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(s.filter(({to:m})=>m===N.STREAM_INITIALIZED),s.once()).subscribe(()=>{this.subscription.add(Se(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===m)?.track?.id},m=>{if(s.isNullable(m))return;const T=this.videoTracks$.getValue().find(({track:v})=>v.id===m)?.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:n.pipe(s.map(m=>m?.id)),onError:i}))},i)),this.subscription.add(Se(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),a(X(this.player,"bufferStateChanged").pipe(s.filter(({mediaType:m})=>m==="video"),s.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),a(X(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:T}})=>{const v=this.player.getDashMetrics(),D=v.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),V=v.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??exports.HttpConnectionType.HTTP1,L={1:!0,0:!1}[D]??void 0;this.params.output.httpConnectionType$.next(V),this.params.output.httpConnectionReused$.next(L),e.hostname$.next(ne(T))}),a(X(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:T,availableFrom:v}}})=>{this.isLive$.next(T),this.availableFrom$.next(v.getTime()),T||e.duration$.next(m);const D=[],V=this.player.getQualityFor("video");let L;for(const M of this.player.getBitrateInfoListFor("video")){const E=M.qualityIndex.toString(10),C=s.videoSizeToQuality(M),I=M.bitrate/1e3,j={width:M.width,height:M.height},te=this.frameRatesByFrameHeight[M.height];if(C){const ae={id:E,quality:C,bitrate:I,size:j,fps:te};D.push({track:ae,bitrateInfo:M}),M.qualityIndex===V&&(L=ae)}}this.videoTracks$.next(D),e.availableVideoTracks$.next(D.map(({track:M})=>M)),L&&e.currentVideoTrack$.next(L),this.videoState.setState(N.STREAM_INITIALIZED),this.videoState.startTransitionTo(N.READY)}),a(X(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const T=m.requestEndDate.getTime()-m.firstByteDate.getTime(),v=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(v,T)}),a(s.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=Ze(this.videoTracks$.getValue().map(({track:V})=>V),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=t.autoVideoTrackLimits.getTransition();v&&e.autoVideoTrackLimits$.next(v.to);const D=this.videoTracks$.getValue().find(({track:V})=>V===T);D?.bitrateInfo&&this.player.setQualityFor("video",D?.bitrateInfo.qualityIndex,!1)}),a(s.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(s.filter(s.isNonNullable))}).pipe(s.filter(({isLive:m})=>m),s.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=X(this.player,"playbackTimeUpdated").pipe(s.map(({time:m})=>m??0));a(s.combine({availableFrom:this.availableFrom$.pipe(s.filter(s.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:T})=>this.params.output.liveTime$.next(m+T*1e3)),a(o.pipe(s.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(X(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(X(this.player,"playbackEnded"),e.endedEvent$),a(X(this.player,"playbackProgress").pipe(s.map(()=>wi(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(X(this.player,"playbackPlaying"),()=>{this.videoState.setState(N.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),a(X(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(N.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(X(this.player,"playbackPaused"),()=>{this.videoState.setState(N.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),a(X(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===N.READY&&this.videoState.setState(N.READY)}),a(this.isLive$,e.isLive$),a(At(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const c=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));a(c,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:h,connectionReused$:l}=ls(this.player);a(h,this.params.output.httpConnectionType$),a(l,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(s.once()),e.firstBytesEvent$),a(X(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(s.combine({isLive:this.isLive$,isShort:e.duration$.pipe(s.map(m=>m<60))}),({isLive:m,isShort:T})=>{const v=!m&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:v}}})}),a(o.pipe(s.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),s.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(X(this.player,"manifestLoaded").pipe(s.once()).subscribe(()=>{this.subscription.add(X(this.player,"playbackPlaying").pipe(s.once(),s.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),a(X(this.player,"manifestLoaded"),m=>{if(m.data?.Period?.AdaptationSet){const T=[];for(const v of m.data?.Period?.AdaptationSet)if(v.contentType==="text"){const D=v.Representation?.id,V=new URL(v.Representation?.BaseURL,m.data?.baseUri).toString(),L="internal",M=v.lang;T.push({id:D,url:V,type:L,language:M})}t.internalTextTracks.startTransitionTo(T)}}),this.subscription.add(Ye(this.video,t.isLooped,i));const{volumeState$:p,looped$:f,playbackRateState$:S,inPiP$:y,inFullscreen$:g,pause$:A,playing$:w}=Re(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:w,pause$:A,tracks$:this.videoTracks$.pipe(s.map(m=>m.map(({track:T})=>T)))}),this.subscription.add(Ce(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Ve(this.video,t.playbackRate,S,i)),this.subscription.add(y.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(N.STOPPED),k(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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=me(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,K.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(),i=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(i?.to!==exports.PlaybackState.PAUSED&&a.state===R.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:s.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:s.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:s.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),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case N.STOPPED:this.prepare();break;default:s.assertNever(e)}break}default:s.assertNever(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}xe(this.video),this.params.output.element$.next(void 0)}}var ft=r=>{switch(r){case"mobile":return s.VideoQuality.Q_144P;case"lowest":return s.VideoQuality.Q_240P;case"low":return s.VideoQuality.Q_360P;case"sd":case"medium":return s.VideoQuality.Q_480P;case"hd":case"high":return s.VideoQuality.Q_720P;case"fullhd":case"full":return s.VideoQuality.Q_1080P;case"quadhd":case"quad":return s.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return s.VideoQuality.Q_2160P}};const si=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Me=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!si(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return si(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function se(){return s.now()}function Di(r){return se()-r}function ai(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,c,d=!1)=>{a(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 ws(r,e,t){const i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function $t(r,e,t,i){const a=window.XMLHttpRequest;let n,o,c,d=!1,u=0,h,l,p=!1,f="arraybuffer",S=7e3,y=2e3,g=()=>{if(d)return;s.assertNonNullable(h);const I=Di(h);let j;if(I<y){j=y-I,setTimeout(g,j);return}y*=2,y>S&&(y=S),o&&o.abort(),o=new a,D()};const A=I=>(n=I,C),w=I=>(l=I,C),m=()=>(f="json",C),T=()=>{if(!d){if(--u>=0){g(),i&&i();return}d=!0,l&&l(),t&&t()}},v=I=>(p=I,C),D=()=>{h=se(),o=new a,o.open("get",r);let I=0,j,te=0;const ae=()=>(s.assertNonNullable(h),Math.max(h,Math.max(j||0,te||0)));if(n&&o.addEventListener("progress",P=>{const H=se();n.updateChunk&&P.loaded>I&&(n.updateChunk(ae(),P.loaded-I),I=P.loaded,j=H)}),c&&(o.timeout=c,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;s.assertNonNullable(o);const P=o.status;if(P>=200&&P<300){if(o.response.byteLength&&n){const H=o.response.byteLength-I;H&&n.updateChunk&&n.updateChunk(ae(),H)}l&&l(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),p){const P=()=>{s.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(te=se(),o.removeEventListener("readystatechange",P))};o.addEventListener("readystatechange",P)}return o.responseType=f,o.send(),C},C={withBitrateReporting:A,withParallel:v,withJSONResponse:m,withRetryCount:I=>(u=I,C),withRetryInterval:(I,j)=>(s.isNonNullable(I)&&(y=I),s.isNonNullable(j)&&(S=j),C),withTimeout:I=>(c=I,C),withFinally:w,send:D,abort:()=>{o&&(o.abort(),o=void 0),d=!0,l&&l()}};return C}const Ds=100,Cs=2e3,_s=500;let xs=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,i){return{start:e,end:t,bytes:i}}_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-_s;if(t-e>Cs){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,c=n.end-n.start;i+=o;const d=n.bytes*o/c;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>Ds&&(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 Rs{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,a,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,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 i=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()-i,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=$t(t,n,()=>a("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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,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}`),i(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=i,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 vt=1e4,Et=3,Ns=300,Ls=2e3,Is=6e4,Bs=10,Vs=1,Ms=500;class Fs{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 xs(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ai(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=ai(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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length;let a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,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)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{ws(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 Rs(Et,vt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,c=null,d=null,u=null,h=!1;const l=()=>{const T=n&&(!h||h===this.rep);return T||t("Not running!"),T},p=(T,v,D)=>{d&&d.abort(),d=$t(this.urlResolver.resolve(T,!1),v,D,()=>this._retryCallback()).withTimeout(vt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Et).withFinally(()=>{d=null}).send()},f=(T,v,D)=>{s.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),v,D,()=>this._retryCallback()).withFinally(()=>{c=null}).send()},S=T=>{const v=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${v}=>${T}`),i.playbackRate=T)},y=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const D=se()-1e4;let V=0;for(let M=0;M<this.bufferStates.length;M++){const E=this.bufferStates[M];T=Math.min(T,E.buf),E.ts<D&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${T} drop=${V} jitter=${this.sourceJitter}`);let L=T-Vs;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?S(1.15):L>1?S(1.1):L>.3?S(1.05):S(1)}},A=T=>{let v;const D=()=>v&&v.start?v.start.length:0,V=P=>v.start[P]/1e3,L=P=>v.dur[P]/1e3,M=P=>v.fragIndex+P,E=(P,H)=>({chunkIdx:M(P),startTS:V(P),dur:L(P),discontinuity:H}),C=()=>{let P=0;if(v&&v.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=H;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let oe=v.dur.length-1;for(;oe>=0&&(Z-=v.dur[oe],!(Z<=0));--oe);P=Math.min(oe,v.dur.length-1-J),P=Math.max(P,0)}return E(P,!0)},I=P=>{const H=D();if(!(H<=0)){if(s.isNonNullable(P)){for(let J=0;J<H;J++)if(V(J)>P)return E(J)}return C()}},j=P=>{const H=D(),J=P?P.chunkIdx+1:0,Z=J-v.fragIndex;if(!(H<=0)){if(!P||Z<0||Z-H>Bs)return t(`Resync: offset=${Z} bChunks=${H} chunk=`+JSON.stringify(P)),C();if(!(Z>=H))return E(J-v.fragIndex,!1)}},te=(P,H,J)=>{u&&u.abort(),u=$t(this.urlResolver.resolve(P,!0,this.lowLatency),H,J,()=>this._retryCallback()).withTimeout(vt).withRetryCount(Et).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,H)=>{te(T,J=>{if(!l())return;v=J;const Z=!!v.lowLatency;Z!==this.lowLatency&&y(Z);let oe=0;for(let Ne=0;Ne<v.dur.length;++Ne)oe+=v.dur[Ne];oe>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(oe/v.dur.length)),a({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,P(I(H))},()=>this._handleNetworkError())},nextChunk:j}},w=()=>{n=!1,c&&c.abort(),d&&d.abort(),u&&u.abort(),s.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:T=>{const{videoElement:v,logger:D}=this.params;let V=A(e.jidxUrl),L,M,E,C,I=0,j,te,ae;const P=()=>{j&&(clearTimeout(j),j=void 0);const U=Math.max(Ms,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=I+U,de=se(),ce=Math.min(1e4,re-de);I=de;const Fe=()=>{u||l()&&V.seek(()=>{l()&&(I=se(),H(),P())})};ce>0?j=window.setTimeout(()=>{this.paused?P():Fe()},ce):Fe()},H=()=>{let U;for(;U=V.nextChunk(C);)C=U,It(U);const re=V.nextChunk(E);if(re){if(E&&re.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?P():(w(),this._initPlayerWith(e));return}Ne(re)}else P()},J=(U,re)=>{if(!l()||!this.sourceBuffer)return;let de,ce,Fe;const pe=$e=>{window.setTimeout(()=>{l()&&J(U,re)},$e)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),pe(100);else{const $e=se(),be=v.currentTime;!this.paused&&v.buffered.length>1&&te===be&&$e-ae>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),te!==be&&(te=be,ae=$e);const Ae=this._getBufferSizeSec();if(Ae>30)D(`Buffered ${Ae} seconds; delaying appendBuffer`),pe(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:$e,buf:Ae}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(Ge){if(Ge.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(de=this.sourceBuffer.buffered.start(0),ce=be,ce-de>4&&this.sourceBuffer.remove(de,ce-3)),pe(1e3);else throw Ge}}},Z=()=>{M&&L&&(D([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(E)]),J(M,function(){M=null,H()}))},oe=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),Ne=U=>{l()&&f(oe(U),(re,de)=>{if(l()){if(de/=1e3,M=re,E=U,o=U.startTS,de){const ce=Math.min(10,U.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}Z()}},()=>this._handleNetworkError())},It=U=>{l()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(oe(U),!1)))},St=U=>{l()&&(e.cachedHeader=U,J(U,()=>{L=!0,Z()}))};n=!0,V.seek(U=>{if(l()){if(I=se(),!U){P();return}C=U,!s.isNullable(T)||U.startTS>T?Ne(U):(E=U,H())}},T),e.cachedHeader?St(e.cachedHeader):p(e.headerUrl,St,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>o},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),s.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,s.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return s.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,f,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),S=l/this.bitrate,f>10&&S>.8||f>15&&S>.5||f>20&&S>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},n=(()=>({updateChunk:(p,f)=>{const S=se();if(this.chunkRateEstimator.addInterval(p,S,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:S-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 l=n.get();if(l&&c&&this.autoQuality){if(d&&l>c&&Di(o)<3e4)return;i(l)}d=this.autoQuality};return{updateChunk:(l,p)=>{const f=n.updateChunk(l,p);return f&&u(),f},notifySwitch:l=>{const p=se();l<c&&(o=p),c=l}}}_fetchManifest(e,t,i){this.manifestRequest=$t(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(vt).withRetryCount(Et).withRetryInterval(Ns,Ls).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Me(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const c=[];return o?.length?(o.forEach((d,u)=>{d.video&&a.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}`),i({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))},Is))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var x;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(x||(x={}));const Os=[x.PAUSED,x.PLAYING,x.READY],Us=[x.PAUSED,x.PLAYING,x.READY];class Hs{subscription=new s.Subscription;video;videoState=new z(x.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new Ee;droppedFramesManager=new Rt;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new xt;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:s.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=_e(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.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ne(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 i=Re(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(s.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===x.READY&&this.videoState.setState(x.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===R.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(s.combine({zeroTime:this.zeroTime$.pipe(s.filter(s.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(Ye(this.video,this.params.desiredState.isLooped,t)).add(Ce(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ve(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{const n=a&&s.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(a.to)}},t)).add(s.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}createLiveDashPlayer(){const e=new Fs({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(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s.isNonNullable(t)?t:Ze(e.map(({track:d})=>d),{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(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((n&&a||a!==o)&&this.setVideoTrack(a),c&&this.setAutoQuality(i),n||c||a!==o){const d=e.find(({track:u})=>u.id===a)?.representation;s.assertNonNullable(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e)?.representation;s.assertNonNullable(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(me(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:s.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const a of t){const n=a.name??a.index.toString(10),o=ft(a.name)??s.videoSizeToQuality(a.video),c=a.bitrate/1e3,d={...a.video};if(!o)continue;const u={id:n,quality:o,bitrate:c,size:d};i.push({track:u,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),s.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=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: ${i}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(t)return;const o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Us.includes(e)&&(o||c)){this.prepare();return}if(a?.to!==exports.PlaybackState.PAUSED&&n.state===R.Requested&&Os.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(me(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const d=a?.from;d&&d===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)})}return;case x.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(x.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(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(me(this.params.source.url,d))}return;default:return s.assertNever(e)}}}var Ci=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?exports.HttpConnectionType.HTTP1:e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}},Be=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){const a=r.start(i)*1e3,n=r.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const js=r=>{const e=document.createElement("a");return e.href=r,e.origin},Ys=r=>{const e=document.createElement("a");return e.href=r,e.host};class _i{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,a,n,o){this._url=e,this._failoverHosts=t,this._completeCb=i,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(this._xhr){if(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(i=>i.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(Ys(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(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const a=this._sourceBuffer.buffered;let n=0;for(let o=0,c=a.length;o<c;o++)n+=a.end(o)-a.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,a,n,o,c){this.abort(()=>{let d=0;const u=Date.now();let h=0,l=0,p=0;const f=y=>{a(Pt._str2ua(y.substr(d))),d=y.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=Je(S)),this._lastXhr=new _i(S,e.failoverHosts,y=>{this._lastXhr=void 0,f(y);const g=Date.now()-u;this._params.onBandwidthChange({size:y.length,duration:g,speed:8*y.length/(g/1e3)}),this._onDashCallback("loading",{size:y.length,done:!0}),n?.()},y=>{if(y.length-d>c&&f(y),l===0){l=Date.now();return}p=y.length-h;const g=Date.now()-l;p>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:p,duration:g,speed:8*p/(g/1e3)}),p=0,h=y.length,l=Date.now()),this._onDashCallback("loading",{size:y.length,done:!1})},o,(y,g,A)=>this._params.onError(y,g,A))})}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(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};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 i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);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 Gs{_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)?)?$/,i=(c,d)=>{const u=c?parseFloat(c.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},a=t.exec(e),n=a?.[1]==="-"?-1:1,o={years:i(a?.[2],n),months:i(a?.[3],n),weeks:i(a?.[4],n),days:i(a?.[5],n),hours:i(a?.[6],n),minutes:i(a?.[7],n),seconds:i(a?.[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Je(i)),new _i(i,t,a=>{this.attachManifest(a,t,js(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,h)=>{const l=u.attributes.getNamedItem(h);return l?l.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const c=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{const h=u.getElementsByTagName("SegmentBase")[0],l=h&&o(h,"indexRange").split("-"),p=h&&h.getElementsByTagName("Initialization")[0],f=p&&o(p,"range").split("-");if(!f||!l){const m=u.parentElement;if(m?.getAttribute("contentType")==="text"){const T=u.getAttribute("id")??void 0,v=(i?i+"/":"")+u.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,D=m.getAttribute("lang")??void 0;v&&d.push({id:T,url:v,language:D})}return}const S=.1,y=Number(u.attributes.getNamedItem("bandwidth")?.value),g=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let A;const w=u.attributes.getNamedItem("frameRate")?.value??void 0;A=w?zt(w):void 0,c.push({width:Number(u.attributes.getNamedItem("width")?.value),height:Number(u.attributes.getNamedItem("height")?.value),bandwidth:y,baseURL:g,failoverHosts:t,indexFrom:Number(l[0]),indexTo:Number(l[1]),initFrom:Number(f[0]),initTo:Number(f[1]),codecs:u.attributes.getNamedItem("codecs")?.value??void 0,mimeType:u.attributes.getNamedItem("mimeType")?.value??void 0,fps:A,bufferSize:S*y/8,bufferLength:S,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:h,url:l})=>{const p=document.createElement("track");l&&p.setAttribute("src",l),u&&p.setAttribute("id",u),h&&p.setAttribute("srclang",h),this._video.appendChild(p)}),this._representations.sort((u,h)=>h.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=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 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 h=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let p=0;p<h;p+=1){const f=u+(o.getUint32(n,!1)&2147483647),S=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/c,toTime:S/c,fromOffset:u,toOffset:f-1}),u=f,d=S}const l=e.refs[e.refs.length-1];l.toTime-l.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,a=>{this._params.onResponseHeaders(a),this._params.onIdxRequestPing(Date.now()-i)},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 i=new t;let a,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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const h=this._appendVector[String(u.fromTime)];h!==a&&(a=h,this._params.onRepresentationPlay(h));let l;if(this._findRef(u.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}l=f.to-this._video.currentTime,l<e.bufferLength&&(this._onDashCallback("buffering"),n!==f.to&&(n=f.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(f);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},l*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=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Pt({mediaSource:i,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),i.duration||(i.duration=this._duration),this._loopTimeout||c(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),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,i=!1,a=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),c=Math.abs(this._video.currentTime-t),d=a||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 i=this._buffer.getByTime(this._video.currentTime),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(c,d)=>this._stream.remove(c,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(c,d)=>this._stream.remove(c,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||s.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 i;for(let a=0;a<t.length;a++){const n=t[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!i||n.fromTime<i.fromTime)&&(i=n)}if(!i){const a=t[t.length-1];if(e>a.toTime)return a}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var B;(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"})(B||(B={}));const qs=[B.PAUSED,B.PLAYING];class zs{videoState=new z(B.STOPPED);subscription=new s.Subscription;video;buffer;dash;representations$=new s.ValueSubject([]);currentRepresentation$=new s.ValueSubject(void 0);params;textTracksManager=new Ee;droppedFramesManager=new Rt;elementSize$=new s.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new s.Subject,responseHeaders$:new s.Subject,manifestReady$:new s.Subject,representationPlay$:new s.Subject,error$:new s.Subject};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),s.merge(this.videoState.stateChangeStarted$.pipe(s.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=_e(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(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ys(this.video),this.dash=new Gs({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:s.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,i=c=>{e.error$.next({id:"DashProvider",category:s.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:c})},a=()=>{const c=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:c},n=Re(this.video),o=(c,d)=>this.subscription.add(c.subscribe(d,i));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.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{s.isNullable(this.params.desiredState.seekState.getState().state!==R.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ye(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ve(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(s.map(c=>c.map(({track:d})=>d)))}),o(At(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(c=>{this.buffer.fill(),e.currentBuffer$.next(c)},i)).add(this.dashLiteEvents.error$.pipe(s.map(({id:c,message:d,thrown:u})=>({id:`DashLite_${c}`,category:s.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(s.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).pipe(s.map(()=>{const c=this.currentRepresentation$.getValue(),d=this.representations$.getValue(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState(),l=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),f=a();u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to);let S;if(!f&&s.isNonNullable(h))S=h;else{const y=Be(this.video.buffered,this.video.currentTime*1e3),g=f?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,A=Math.min(y/g,1);S=Ze(d.map(({track:m})=>m),{container:p,throughput:l,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:A,playbackRate:this.video.playbackRate,current:d.find(({representation:m})=>m===c)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const w=t.autoVideoTrackLimits.getTransition();w&&e.autoVideoTrackLimits$.next(w.to)}return s.isNonNullable(S)?d.find(({track:y})=>y.id===S)?.representation:void 0}),s.filterChanged()).subscribe(this.currentRepresentation$,i)).add(s.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(s.filter(c=>c.to===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(s.filter(s.isNonNullable))}).pipe(s.once()).subscribe(()=>this.videoState.setState(B.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(s.filter(s.isNonNullable),s.filterChanged((c,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?c.height<=d.height:c===d)).subscribe(c=>{const d=Be(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(c,!0),this.params.output.hostname$.next(ne(c.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(c=>{const{type:d,reused:u}=Ci(c);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(s.once(),s.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,i)).add(this.dashLiteEvents.representationPlay$.pipe(s.filter(s.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return s.assertNever(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const a of e){const n=a.name??a.id??a.height.toString(10),o=(a.name&&ft(a.name))??s.videoSizeToQuality(a),c=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!o)continue;const h={id:n,quality:o,bitrate:c,size:d,fps:u};i.push({track:h,representation:a})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),t?.length>0){const a=[];for(const n of t){const o=n.id||`${n.language}_${Date.now()}`;a.push({id:o,type:"internal",url:n.url||"",language:n.language,isAuto:n.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(a)}this.videoState.setState(B.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===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 s.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(){Me(this.video).then(e=>{e||(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.ErrorCategory.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=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: ${i}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(B.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(a?.to!==exports.PlaybackState.PAUSED&&n.state===R.Requested&&qs.includes(e)&&this.seek(n.position,n.forcePrecise),e){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}}var ee;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(ee||(ee={}));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 he;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(he||(he={}));var F;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(F||(F={}));var Xe;(function(r){r.MP4="mp4",r.WEBM="webm"})(Xe||(Xe={}));var Dt;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Dt||(Dt={}));var Q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Q||(Q={}));class ri{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];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 xi extends ri{constructor(){super(),this.listeners||ri.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 Ri=class{constructor(){Object.defineProperty(this,"signal",{value:new xi,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 i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ri.prototype[Symbol.toStringTag]="AbortController",xi.prototype[Symbol.toStringTag]="AbortSignal");function Ni(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 Qs(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!Ni({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,h){let l;h&&h.signal&&(l=h.signal,delete h.signal);const p=new t(u,h);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const h=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(h){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(h.aborted)return Promise.reject(l);const p=new Promise((f,S)=>{h.addEventListener("abort",()=>S(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,o(d,u)])}return o(d,u)},Request:n}}const Nt=Ni({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Li=Nt?Qs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Nt?Li.fetch:window.fetch;Nt?Li.Request:window.Request;const We=Nt?Ri:window.AbortController;var jt=(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 Ws=(r,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Js=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ni=Js?Ws:window.requestIdleCallback;let Ii=!1;try{Ii=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class Xs{bufferFull$=new s.Subject;error$=new s.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(i=>{const a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Ii&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:s.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:s.assertNever(t)}}}var oi=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};class ke{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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Bi extends ke{}class Ks extends ke{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 i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Zs extends ke{parseChildrenBoxes(){return et(this.content)}}class ea extends ke{data;constructor(e){super(e),this.data=this.content}}class mt extends ke{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class ta extends mt{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 i=this.readUint32();const a=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const c=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:d})}}}class ia extends ke{parseChildrenBoxes(){return et(this.content)}}class sa extends ke{parseChildrenBoxes(){return et(this.content)}}var je;(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"})(je||(je={}));class aa extends mt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=je.MONOSCOPIC;break;case 1:this.stereoMode=je.TOP_BOTTOM;break;case 2:this.stereoMode=je.LEFT_RIGHT;break;case 3:this.stereoMode=je.STEREO_CUSTOM;break;case 4:this.stereoMode=je.RIGHT_LEFT;break}this.cursor+=1}}class ra extends mt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class na extends mt{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 oa extends ke{parseChildrenBoxes(){return et(this.content)}}class ca extends mt{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 ua extends ke{parseChildrenBoxes(){return et(this.content)}}class da extends ke{parseChildrenBoxes(){return et(this.content)}}const la={ftyp:Ks,moov:Zs,mdat:ea,sidx:ta,trak:ia,mdia:oa,tkhd:ca,minf:ua,sv3d:sa,st3d:aa,prhd:ra,proj:da,equi:na,unknown:Bi};class ha{createBox(e,t){const i=la[e];return i?new i(t):new Bi(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Lt.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Lt=new ha;function ut(r,e){const t=new TextDecoder("ascii");let i=r.byteOffset,a=[];for(;i<r.byteLength;){const n=t.decode(new DataView(r.buffer,i,1));if(n===e[a.length]?a.push(n):a=[],a.length===4&&a.join("")===e){const c=new DataView(r.buffer,i-7,4).getUint32(0);return i-7+c>r.byteLength?null:Lt.createBox(e,new DataView(r.buffer,i-7))}i++}return null}function pa(r,e){const t=[];let i=0;for(;i<r.byteLength;){const a=ut(new DataView(r.buffer,r.byteOffset+i,r.byteLength-i),e);if(a)t.push(a),i+=a.size+a.source.byteOffset;else break}return t}function et(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Lt.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const fa=new TextDecoder("ascii"),ma=r=>fa.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Sa=r=>{const e=Lt.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=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:F.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,c})},ba=r=>{const e=pa(r,"mdat");if(e.length){const t=e.reduce((i,a)=>i+a.size,0);return new DataView(r.buffer,r.byteOffset,t)}return null},ga=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Dt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ut(r,"sv3d")){e.is3dVideo=!0;const i=ut(r,"st3d");i&&(e.stereoMode=i.stereoMode);const a=ut(r,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=ut(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},ya={validateData:ma,parseInit:ga,getIndexRange:()=>{},parseSegments:Sa,parseFeedableSegmentChunk:ba};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 $;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})($||($={}));const ci={[b.EBML]:{type:$.Master},[b.EBMLVersion]:{type:$.UnsignedInteger},[b.EBMLReadVersion]:{type:$.UnsignedInteger},[b.EBMLMaxIDLength]:{type:$.UnsignedInteger},[b.EBMLMaxSizeLength]:{type:$.UnsignedInteger},[b.DocType]:{type:$.String},[b.DocTypeVersion]:{type:$.UnsignedInteger},[b.DocTypeReadVersion]:{type:$.UnsignedInteger},[b.Void]:{type:$.Binary},[b.Segment]:{type:$.Master},[b.SeekHead]:{type:$.Master},[b.Seek]:{type:$.Master},[b.SeekID]:{type:$.Binary},[b.SeekPosition]:{type:$.UnsignedInteger},[b.Info]:{type:$.Master},[b.TimestampScale]:{type:$.UnsignedInteger},[b.Duration]:{type:$.Float},[b.Tracks]:{type:$.Master},[b.TrackEntry]:{type:$.Master},[b.Video]:{type:$.Master},[b.Projection]:{type:$.Master},[b.ProjectionType]:{type:$.UnsignedInteger},[b.ProjectionPrivate]:{type:$.Master},[b.Chapters]:{type:$.Master},[b.Cluster]:{type:$.Master},[b.Timestamp]:{type:$.UnsignedInteger},[b.SilentTracks]:{type:$.Master},[b.SilentTrackNumber]:{type:$.UnsignedInteger},[b.Position]:{type:$.UnsignedInteger},[b.PrevSize]:{type:$.UnsignedInteger},[b.SimpleBlock]:{type:$.Binary},[b.BlockGroup]:{type:$.Master},[b.EncryptedBlock]:{type:$.Binary},[b.Attachments]:{type:$.Master},[b.Tags]:{type:$.Master},[b.Cues]:{type:$.Master},[b.CuePoint]:{type:$.Master},[b.CueTime]:{type:$.UnsignedInteger},[b.CueTrackPositions]:{type:$.Master},[b.CueTrack]:{type:$.UnsignedInteger},[b.CueClusterPosition]:{type:$.UnsignedInteger},[b.CueRelativePosition]:{type:$.UnsignedInteger},[b.CueDuration]:{type:$.UnsignedInteger},[b.CueBlockNumber]:{type:$.UnsignedInteger},[b.CueCodecState]:{type:$.UnsignedInteger},[b.CueReference]:{type:$.Master},[b.CueRefTime]:{type:$.UnsignedInteger}},Vi=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 i=Ct(r,t),a=i in ci,n=a?ci[i].type:$.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,h=Ct(d),l=u*2**((c-1)*8)+h,p=t+c;let f;return p+l>r.byteLength?f=new DataView(r.buffer,r.byteOffset+p):f=new DataView(r.buffer,r.byteOffset+p,l),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:p,tagSize:p+l,value:f,valueSize:l}},Ct=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Te=(r,e)=>{switch(e){case $.SignedInteger:return r.getInt8(0);case $.UnsignedInteger:return Ct(r);case $.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case $.String:return new TextDecoder("ascii").decode(r);case $.UTF8:return new TextDecoder("utf-8").decode(r);case $.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case $.Master:return r;case $.Binary:return r;default:s.assertNever(e)}},Ke=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),a=Vi(i);if(!e(a))return;a.type===$.Master&&Ke(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},Ta=r=>{if(r.getUint32(0)!==b.EBML)return!1;let e,t,i;const a=Vi(r);return Ke(a.value,({tag:n,type:o,value:c})=>(n===b.EBMLReadVersion?e=Te(c,o):n===b.DocType?t=Te(c,o):n===b.DocTypeReadVersion&&(i=Te(c,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Mi=[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],va=[b.Timestamp,b.SilentTracks,b.SilentTrackNumber,b.Position,b.PrevSize,b.SimpleBlock,b.BlockGroup,b.EncryptedBlock],Ea=r=>{let e,t,i,a,n=!1,o=!1,c=!1,d,u,h=!1;const l=0;return Ke(r,({tag:p,type:f,value:S,valueSize:y})=>{if(p===b.SeekID){const g=Te(S,f);u=Ct(g)}else p!==b.SeekPosition&&(u=void 0);return p===b.Segment?(e=S.byteOffset,t=S.byteOffset+y):p===b.Info?n=!0:p===b.SeekHead?o=!0:p===b.TimestampScale?i=Te(S,f):p===b.Duration?a=Te(S,f):p===b.SeekPosition&&u===b.Cues?d=Te(S,f):p===b.Tracks?Ke(S,({tag:g,type:A,value:w})=>g===b.ProjectionType?(h=Te(w,A)===1,!1):!0):n&&o&&Mi.includes(p)&&(c=!0),!c}),s.assertNonNullable(e,"Failed to parse webm Segment start"),s.assertNonNullable(t,"Failed to parse webm Segment end"),s.assertNonNullable(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:Dt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ka=r=>{if(s.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},$a=(r,e)=>{let t=!1,i=!1;const a=c=>s.isNonNullable(c.time)&&s.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&&a(o)&&n.push(o),o={};break;case b.CueTime:o&&(o.time=Te(u,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:o&&(o.position=Te(u,d));break;default:t&&Mi.includes(c)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((c,d)=>{const{time:u,position:h}=c,l=n[d+1];return{status:F.NONE,time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},Aa=r=>{let e=0,t=!1;try{Ke(r,i=>i.tag===b.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):va.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[b.SimpleBlock,b.BlockGroup,b.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Pa={validateData:Ta,parseInit:Ea,getIndexRange:ka,parseSegments:$a,parseFeedableSegmentChunk:Aa},Fi=1e4,wa=3e4,Da=5e3,Ca=Fi,_a=({id:r,width:e,height:t,bitrate:i,fps:a,quality:n})=>{const o=(n?ft(n):void 0)??s.videoSizeToQuality({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a}},xa=({id:r,bitrate:e})=>({id:r,bitrate:e}),Ra=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},Na=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),kt=r=>{const e=[];let t=0,i=r.length-1;for(;t<Fi&&i>=0;)e.unshift(r[i]),t+=r[i].time.to-r[i].time.from,i--;return e};class ui{onLastSegment$=new s.ValueSubject(!1);fullyBuffered$=new s.ValueSubject(!1);playingRepresentation$=new s.ValueSubject(void 0);playingRepresentationInit$=new s.ValueSubject(void 0);error$=new s.Subject;gaps=[];isSeekingLive=!1;subscription=new s.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new We;destroyAbortController=new We;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:c,compatibilityMode:d=!1,manifest:u}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=c,this.isLive=!!u?.dynamic,this.container=i,i){case Xe.MP4:this.containerParser=ya;break;case Xe.WEBM:this.containerParser=Pa;break;default:s.assertNever(i)}this.initData=new Map(a.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=s.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);s.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 Xs(this.sourceBuffer),this.subscription.add(s.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:s.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(s.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:s.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const c=Math.min(this.bufferLimit,oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=c,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),a=this.segments.get(t.id),n=this.parsedInitData.get(t.id);s.assertNonNullable(i,"No init buffer for starting representation"),s.assertNonNullable(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=s.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);s.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),a=this.initData.get(e);if(s.isNullable(a)||s.isNullable(i)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),i=this.segments.get(e),s.assertNonNullable(i,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);const n=this.getCurrentPosition();s.isNonNullable(n)&&(this.searchGaps(i,t),this.maintain(n))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new We,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(s.isNullable(e)||s.isNullable(this.downloadingRepresentationId)||s.isNullable(this.playingRepresentationId)||s.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(s.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Be(this.sourceBuffer.buffered,e),l=a?a.time.to+100:-1/0;a&&h>=a.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&oi(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Be(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<h);return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(i,t.segmentReference.type,n),c.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(c.includes(a))u="high";else{const h=c.at(0);h&&h.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(c,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===F.FED&&!c.length&&Be(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=i.at(-1);d&&d.status===F.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const a of e)a.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from}),i=a.time.to;s.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=s.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const c of this.representations.keys()){const d=e.find(l=>l.id===c);d&&this.representations.set(c,d);const u=this.representations.get(c);if(!u)return;const h=kt(u.segmentReference.segments);this.segments.set(u.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);s.assertNonNullable(i);const a=kt(i.segmentReference.segments),n=this.initData.get(i.id);if(s.assertNonNullable(n,"No init buffer for starting representation"),s.assertNonNullable(a,"No segments for starting representation"),!(n instanceof ArrayBuffer))return;const o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t)return;const i=t.segmentReference.segments.map(c=>({...c,status:F.NONE,size:void 0})),a=this.segments.get(t.id)??[],n=a.at(-1)?.time.to??0,o=i?.findIndex(c=>Math.round(n)>=Math.round(c.time.from)&&Math.round(n)<=Math.round(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const c=kt(i);this.segments.set(t.id,[...c])}else{const c=i.slice(o+1);this.segments.set(t.id,[...a,...c])}}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(n=>n.time.from<=e&&n.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.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();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const a=e.findIndex(({status:l,time:{from:p,to:f}},S)=>{const y=p<=i&&f>=i,g=p>i||y||S===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&p<=i+A||f<=i+A;return(l===F.NONE||l===F.PARTIALLY_EJECTED&&g&&w&&this.sourceBuffer&&!jt(this.sourceBuffer.buffered,i))&&g&&w});if(a===-1)return[];if(t!==he.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,c=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=a;l<n.length&&(o<=u||c<=h);l++){const p=n[l];if(o+=p.byte.to+1-p.byte.from,c+=p.time.to+1-p.time.from,p.status===F.NONE||p.status===F.PARTIALLY_EJECTED)d.push(p);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:c}=t.segmentReference;switch(c){case he.BYTE_RANGE:{a=t.segmentReference.url,n={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case he.TEMPLATE:{const u=e.at(0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:s.assertNever(c)}for(const u of o)u.status=F.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await s.abortable(d,async function*(){const u=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,u))}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(a,{range:n,onProgress:(u,h)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,h,d)}catch(l){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:d,priority:i}).then(()=>this.failedDownloads=0,u=>{if(u.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(u)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&s.isNonNullable(i)&&(t=Be(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:s.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},c=l=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),l.segment.status=F.FED,"size"in l.segment&&(l.segment.size=l.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const f of this.segments.get(p.id)??[])f.status===F.FED&&f.time.from===l.segment.time.from&&f.time.to===l.segment.time.to&&(f.status=F.NONE);this.activeSegments.delete(l),this.detectGapsWhenIdle(t,[l.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,h=e.byteLength;for(const l of this.activeSegments){const{segment:p}=l,f=u===he.BYTE_RANGE,S=f?p.byte.to-p.byte.from+1:h;if(l.representationId!==t||!(!f||p.byte.from>=i&&p.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const g=f?p.byte.from-i:0,A=f?p.byte.to-i:e.byteLength,w=g<a,m=A<=a;if(p.status===F.DOWNLOADING&&w&&m){p.status=F.DOWNLOADED,this.activeSegments.delete(l);const T=new DataView(e.buffer,e.byteOffset+g,S);this.sourceBufferTaskQueue.append(T,n).then(v=>v&&!n.aborted?c(l):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&w&&(l.loadedBytes=Math.min(S,a-g),l.loadedBytes>l.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+g+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===S?T:this.containerParser.parseFeedableSegmentChunk(T);v?.byteLength&&(p.status=F.PARTIALLY_FED,l.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,n).then(D=>{if(n.aborted)o();else if(D)l.fedBytes+=v.byteLength,l.fedBytes===S&&c(l);else{if(l.feedingBytes<S)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===F.PARTIALLY_FED||e.status===F.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=F.NONE),e.status=F.PARTIALLY_EJECTED):e.status=F.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=ni(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?s.abortable(this.destroyAbortController.signal,async function*(){const c=s.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,a)).then(async c=>{if(!c)return;const{init:d,dataView:u,segments:h}=c,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,this.isLive?kt(h):h),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,c=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:s.ErrorCategory.WTF,message:"loadInit threw",thrown:c})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||s.isNullable(e)||this.sourceBuffer.updating)return!1;let a=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 h="size"in u?u.size??0:u.byte.to-u.byte.from;a+=h};for(const u of this.segments.values())for(const h of u){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;h.status===F.FED&&d(h)}if(c=isFinite(n)&&isFinite(o),!c){a=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const h of u){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;h.status===F.FED&&d(h)}}if(c=isFinite(n)&&isFinite(o),!c)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const h=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===F.NONE&&Math.round(f.time.from)<=Math.round(h)&&Math.round(f.time.to)>=Math.round(l)){n=h,o=l;break}}if(c=isFinite(n)&&isFinite(o),!c&&i){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+u&&l.status===F.FED&&d(l)}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)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&c>=i.time.to){a=void 0;break}c>i.time.from&&c<i.time.to&&(a.from=c),o<i.time.to&&o>i.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=ni(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:s.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(s.isNullable(this.sourceBuffer)||s.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==F.FED&&n!==F.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),c=Math.ceil(a.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=c),u=e.filter(h=>o>=h.from-t&&o<=h.to+t||c>=h.from-t&&c<=h.to+t);d||(u.length===1?a.status=F.PARTIALLY_EJECTED:a.status=F.NONE)}}}var Qe;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Qe||(Qe={}));class La{throughputEstimator;requestQuic;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);abortAllController=new We;subscription=new s.Subscription;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=s.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Je(t));const i=yield ht(t,{signal:this.abortAllController.signal}).catch(nt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=s.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Qe.HEADER:Qe.PARAM,range:i,onProgress:a,priority:n="auto",signal:o,measureThroughput:c=!0}={}){let d=e;const u=new Headers;if(i)switch(t){case Qe.HEADER:{u.append("Range",`bytes=${i.from}-${i.to}`);break}case Qe.PARAM:{const E=new URL(d,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),d=E.toString();break}default:s.assertNever(t)}this.requestQuic&&(d=Je(d));let h=this.abortAllController.signal,l;if(o){const E=new We;if(l=s.merge(s.fromEvent(this.abortAllController.signal,"abort"),s.fromEvent(o,"abort")).subscribe(()=>{try{E.abort()}catch(C){nt(C)}}),this.abortAllController.signal.aborted||o.aborted)try{E.abort()}catch(C){nt(C)}h=E.signal}const p=s.now(),f=yield ht(d,{priority:n,headers:u,signal:h}).catch(nt),S=s.now();if(this.throughputEstimator?.addRawRtt(S-p),!f)return l?.unsubscribe(),null;if(!f.ok||!f.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const y=parseInt(f.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!y){const E=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(E.byteLength,s.now()-S),a?.(new DataView(E),E.byteLength),l?.unsubscribe(),E}if(!a&&!c)return l?.unsubscribe(),f.arrayBuffer();const[g,A]=f.body.tee(),w=g.getReader();c&&this.throughputEstimator?.trackStream(A);let m=0;const T=new ArrayBuffer(y),v=new Uint8Array(T),D=new DataView(T);let V=!1;const L=E=>{l?.unsubscribe(),V=!0,nt(E)},M=s.abortable(h,async function*({done:E,value:C}){if(m===0&&this.lastRequestFirstBytes$.next(s.now()-p),h.aborted){l?.unsubscribe();return}!E&&C&&(v.set(C,m),m+=C.byteLength,a?.(D,m),yield w?.read().then(M,L))}.bind(this));return yield w?.read().then(M,L),l?.unsubscribe(),V?null:T}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:a}=e;switch(a){case he.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case he.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:s.assertNever(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==he.BYTE_RANGE)return null;const{from:a,to:n}=e.initRange;let o=a,c=n,d=!1,u,h;e.indexRange&&(u=e.indexRange.from,h=e.indexRange.to,d=n+1===u,d&&(o=Math.min(u,a),c=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:c},priority:i,measureThroughput:!1});if(!l)return null;const p=new DataView(l,a-o,n-o+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),S=e.indexRange??t.getIndexRange(f);if(!S)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,S.from-o,S.to-S.from+1);else{const A=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!A)return null;y=new DataView(A)}const g=t.parseSegments(y,f,S);return{init:f,dataView:new DataView(l),segments:g}}.bind(this));fetchTemplateRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==he.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(o=>({...o,status:F.NONE,size:void 0})),dataView:new DataView(a)}:null}.bind(this))}const nt=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},di=r=>{if(!r.startsWith("P"))return;const e=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,n={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Ft=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(c,d)=>s.isNullable(n)?c:s.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Ia=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],c=o.children,d=n.getAttribute("type")==="dynamic",u=n.getAttribute("availabilityStartTime"),h=u?new Date(u).getTime():void 0;let l;const p=n.getAttribute("mediaPresentationDuration"),f=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)l=di(p);else if(f){const m=di(f);s.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let g=0;const A=n.getAttribute("profiles")?.split(",")??[],w=A.includes(wt.WEBM_AS_IN_FFMPEG)||A.includes(wt.WEBM_AS_IN_SPEC)?Xe.WEBM:Xe.MP4;for(const m of c){const T=m.getAttribute("mimeType"),v=m.getAttribute("codecs"),D=m.getAttribute("contentType")??T?.split("/")[0],V=m.getAttribute("profiles")?.split(",")??[],L=m.querySelectorAll("Representation"),M=m.querySelector("SegmentTemplate");if(D===ee.TEXT){for(const E of L){const C=E.getAttribute("id")||"",I=m.getAttribute("lang"),j=E.querySelector("BaseURL")?.textContent?.trim()??"",te=new URL(j,e).toString(),ae=C.includes("_auto");a[ee.TEXT].push({id:C,lang:I,isAuto:ae,kind:ee.TEXT,url:te})}continue}for(const E of L){const C=E.getAttribute("mimeType")??T,I=E.getAttribute("codecs")??v??"",j=E.getAttribute("contentType")??C?.split("/")[0]??D,te=m.getAttribute("profiles")?.split(",")??[],ae=parseInt(E.getAttribute("width")??"",10),P=parseInt(E.getAttribute("height")??"",10),H=parseInt(E.getAttribute("bandwidth")??"",10)/1e3,J=E.getAttribute("frameRate")??"",Z=E.getAttribute("quality")??void 0,oe=J?zt(J):void 0,Ne=E.getAttribute("id")??(g++).toString(10),It=j==="video"?`${P}p`:j==="audio"?`${H}Kbps`:I,St=`${Ne}@${It}`,U=E.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(U,e).toString(),de=[...A,...V,...te];let ce;const Fe=E.querySelector("SegmentBase"),pe=E.querySelector("SegmentTemplate")??M;if(Fe){const be=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ae,Ge]=be.split("-").map(qe=>parseInt(qe,10)),tt={from:Ae,to:Ge},it=E.querySelector("SegmentBase")?.getAttribute("indexRange"),[Bt,bt]=it?it.split("-").map(qe=>parseInt(qe,10)):[],st=it?{from:Bt,to:bt}:void 0;ce={type:he.BYTE_RANGE,url:re,initRange:tt,indexRange:st}}else if(pe){const be={representationId:E.getAttribute("id")??void 0,bandwidth:E.getAttribute("bandwidth")??void 0},Ae=parseInt(pe.getAttribute("timescale")??"",10),Ge=pe.getAttribute("initialization")??"",tt=pe.getAttribute("media"),it=parseInt(pe.getAttribute("startNumber")??"",10)??1,Bt=Ft(Ge,be);if(!tt)throw new ReferenceError("No media attribute in SegmentTemplate");const bt=pe.querySelectorAll("SegmentTimeline S")??[],st=[];let qe=0;if(bt.length){let Vt=it,Pe=0;for(const at of bt){const Le=parseInt(at.getAttribute("d")??"",10),Oe=parseInt(at.getAttribute("r")??"",10)||0,gt=parseInt(at.getAttribute("t")??"",10);Pe=Number.isFinite(gt)?gt:Pe;const Mt=Le/Ae*1e3,Wt=Pe/Ae*1e3;for(let yt=0;yt<Oe+1;yt++){const zi=Ft(tt,{...be,segmentNumber:Vt.toString(10),segmentTime:(Pe+yt*Le).toString(10)}),Jt=(Wt||0)+yt*Mt,Qi=Jt+Mt;Vt++,st.push({time:{from:Jt,to:Qi},url:zi})}Pe+=(Oe+1)*Le,qe+=(Oe+1)*Mt}}else if(s.isNonNullable(l)){const Pe=parseInt(pe.getAttribute("duration")??"",10)/Ae*1e3,at=Math.ceil(l/Pe);let Le=0;for(let Oe=1;Oe<at;Oe++){const gt=Ft(tt,{...be,segmentNumber:Oe.toString(10),segmentTime:Le.toString(10)});st.push({time:{from:Le,to:Le+Pe},url:gt}),Le+=Pe}}ce={type:he.TEMPLATE,baseUrl:re,initUrl:Bt,totalSegmentsDurationMs:qe,segments:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!C)continue;const $e={video:ee.VIDEO,audio:ee.AUDIO,text:ee.TEXT}[j];$e&&a[$e].push({id:St,kind:$e,segmentReference:ce,profiles:de,duration:l,bitrate:H,mime:C,codecs:I,width:ae,height:P,fps:oe,quality:Z})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:w,representations:a}},Yt=1e3,li=["timeupdate","progress","play","seeked","stalled","waiting"];var le;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(le||(le={}));let Ba=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new s.Subscription;representationSubscription=new s.Subscription;fetcher;state$=new z(le.NONE);currentVideoRepresentation$=new s.ValueSubject(void 0);currentVideoRepresentationInit$=new s.ValueSubject(void 0);error$=new s.Subject;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);isLive$=new s.ValueSubject(!1);liveDuration$=new s.ValueSubject(0);liveAvailabilityStartTime$=new s.ValueSubject(void 0);bufferLength$=new s.ValueSubject(0);liveLoadBufferLength$=new s.ValueSubject(0);forceEnded$=new s.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new We;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new La({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=s.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=me(t,i,K.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:s.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=s.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:s.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return this.manifest;let t;try{t=Ia(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:s.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;const i=({kind:a,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||a===ee.TEXT);return this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([a,n])=>[a,n.filter(i)]))}}.bind(this));async seekLive(e){s.assertNonNullable(this.element),this.manifestUrlString=me(this.manifestUrlString,e,K.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=s.abortable(this.destroyController.signal,async function*(e,t){s.assertNonNullable(this.manifest),s.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(le.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new ui(ee.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s.isNonNullable(t)&&(this.audioBufferManager=new ui(ee.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(s.interval(Yt).subscribe(o=>{if(this.element?.paused){const c=Zt(this.manifestUrlString,K.DASH_CMAF_OFFSET_P);this.manifestUrlString=me(this.manifestUrlString,c+1e3,K.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(s.merge(...li.map(o=>s.fromEvent(this.element,o))).pipe(s.throttle(Yt),s.map(o=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(c=>{let d=0;if(c){const u=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-u}this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async c=>{s.assertNonNullable(this.element);const d=this.element.playbackRate,u=Zt(this.manifestUrlString,K.DASH_CMAF_OFFSET_P),h=wa*d,l=Ca*d,p=Da*d;o=c>o?c:o;const f=u===0&&c<p,S=u!==0&&c<h+p&&c>=h,y=u!==0&&c<h;if(y||S){const g=o-(h+l),A=Math.trunc(u+g/d);let w;c?A>0?w=A:w=0:w=u,this.manifestUrlString=me(this.manifestUrlString,w,K.DASH_CMAF_OFFSET_P)}(f||y||S)&&(await this.updateLive(),o=0)}))}const a=s.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(s.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=s.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(s.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(s.merge(this.forceEnded$,s.combine({allBuffersFull:a,someBufferEnded:n}).pipe(s.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:s.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(s.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.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))),s.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){s.assertNonNullable(this.element),this.state$.setState(le.RUNNING),this.subscription.add(s.merge(...li.map(e=>s.fromEvent(this.element,e)),s.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:s.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(s.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(s.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[ee.VIDEO]:this.videoBufferManager,[ee.AUDIO]:this.audioBufferManager,[ee.TEXT]:null}[e]?.switchTo(t)}seek(e,t){s.assertNonNullable(this.element),s.assertNonNullable(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),jt(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(le.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.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=s.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:s.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const a=Math.max(...i);a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class Va{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Ma{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const a=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var Fa=`#define GLSLIFY 1
|
|
29
|
+
`}),E}return u?.recordSwitch(L),L};var ne=r=>new URL(r).hostname;const Ps=300,At=(r,e=Ps)=>new s.Observable(t=>{const{width:i,height:a}=r.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(ts(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),s.isNonNullable(d)&&s.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(r),()=>n.disconnect()});class Rt{onDroopedVideoFramesLimit$=new s.Subject;subscription=new s.Subscription;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new s.Subject;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(s.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=s.interval(this.droppedFramesChecker.checkTime).pipe(s.filter(()=>this.playing),s.filter(()=>{const a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(s.debounce(this.droppedFramesChecker.checkTime)),i=s.merge(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!s.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,n=1-(i-a)/i;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&s.isHigher(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)};onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){const t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>s.isLower(i,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const rt={};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 X=(r,e)=>new s.Observable(t=>{const i=a=>t.next(a);return r.on(e,i),()=>r.off(e,i)});class ii{subscription=new s.Subscription;videoState=new z(N.DOWNLOADING_LIB);video;player;params;textTracksManager=new Ee;droppedFramesManager=new Rt;videoTracks$=new s.ValueSubject([]);frameRatesByFrameHeight={};isLive$=new s.ValueSubject(void 0);maxSeekBackTime$=new s.ValueSubject(1/0);availableFrom$=new s.ValueSubject(void 0);elementSize$=new s.ValueSubject(void 0);liveOffset=new xt;constructor(e){this.video=_e(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(ne(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:s.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${a?.toString?.()}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(rt.MediaPlayer=a.MediaPlayer,rt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(rt.MediaPlayer,"dashjs not loaded"),s.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(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?zt(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&ps(this.player),ds(this.player),this.params.tuning.requestQuick&&hs(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(N.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:s.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},a=(m,T)=>this.subscription.add(m.subscribe(T,i));a(At(this.video),this.elementSize$),a(X(this.player,"error").pipe(s.map(m=>{const T=typeof m.error=="object"?m.error.code:m.error,v=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${T}`,message:v}})),e.error$),a(X(this.player,"playbackError").pipe(s.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=X(this.player,"qualityChangeRendered").pipe(s.filter(({mediaType:m})=>m==="video"),s.map(({newQuality:m})=>this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===m)?.track));n.pipe(s.filter(s.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(s.filter(({to:m})=>m===N.STREAM_INITIALIZED),s.once()).subscribe(()=>{this.subscription.add(Se(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===m)?.track?.id},m=>{if(s.isNullable(m))return;const T=this.videoTracks$.getValue().find(({track:v})=>v.id===m)?.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:n.pipe(s.map(m=>m?.id)),onError:i}))},i)),this.subscription.add(Se(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),a(X(this.player,"bufferStateChanged").pipe(s.filter(({mediaType:m})=>m==="video"),s.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),a(X(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:T}})=>{const v=this.player.getDashMetrics(),D=v.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),V=v.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??exports.HttpConnectionType.HTTP1,L={1:!0,0:!1}[D]??void 0;this.params.output.httpConnectionType$.next(V),this.params.output.httpConnectionReused$.next(L),e.hostname$.next(ne(T))}),a(X(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:T,availableFrom:v}}})=>{this.isLive$.next(T),this.availableFrom$.next(v.getTime()),T||e.duration$.next(m);const D=[],V=this.player.getQualityFor("video");let L;for(const M of this.player.getBitrateInfoListFor("video")){const E=M.qualityIndex.toString(10),C=s.videoSizeToQuality(M),I=M.bitrate/1e3,j={width:M.width,height:M.height},te=this.frameRatesByFrameHeight[M.height];if(C){const ae={id:E,quality:C,bitrate:I,size:j,fps:te};D.push({track:ae,bitrateInfo:M}),M.qualityIndex===V&&(L=ae)}}this.videoTracks$.next(D),e.availableVideoTracks$.next(D.map(({track:M})=>M)),L&&e.currentVideoTrack$.next(L),this.videoState.setState(N.STREAM_INITIALIZED),this.videoState.startTransitionTo(N.READY)}),a(X(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const T=m.requestEndDate.getTime()-m.firstByteDate.getTime(),v=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(v,T)}),a(s.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=Ze(this.videoTracks$.getValue().map(({track:V})=>V),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=t.autoVideoTrackLimits.getTransition();v&&e.autoVideoTrackLimits$.next(v.to);const D=this.videoTracks$.getValue().find(({track:V})=>V===T);D?.bitrateInfo&&this.player.setQualityFor("video",D?.bitrateInfo.qualityIndex,!1)}),a(s.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(s.filter(s.isNonNullable))}).pipe(s.filter(({isLive:m})=>m),s.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=X(this.player,"playbackTimeUpdated").pipe(s.map(({time:m})=>m??0));a(s.combine({availableFrom:this.availableFrom$.pipe(s.filter(s.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:T})=>this.params.output.liveTime$.next(m+T*1e3)),a(o.pipe(s.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(X(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(X(this.player,"playbackEnded"),e.endedEvent$),a(X(this.player,"playbackProgress").pipe(s.map(()=>wi(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(X(this.player,"playbackPlaying"),()=>{this.videoState.setState(N.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),a(X(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(N.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(X(this.player,"playbackPaused"),()=>{this.videoState.setState(N.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),a(X(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===N.READY&&this.videoState.setState(N.READY)}),a(this.isLive$,e.isLive$),a(At(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const c=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));a(c,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:h,connectionReused$:l}=ls(this.player);a(h,this.params.output.httpConnectionType$),a(l,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(s.once()),e.firstBytesEvent$),a(X(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(s.combine({isLive:this.isLive$,isShort:e.duration$.pipe(s.map(m=>m<60))}),({isLive:m,isShort:T})=>{const v=!m&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:v}}})}),a(o.pipe(s.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),s.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(X(this.player,"manifestLoaded").pipe(s.once()).subscribe(()=>{this.subscription.add(X(this.player,"playbackPlaying").pipe(s.once(),s.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),a(X(this.player,"manifestLoaded"),m=>{if(m.data?.Period?.AdaptationSet){const T=[];for(const v of m.data?.Period?.AdaptationSet)if(v.contentType==="text"){const D=v.Representation?.id,V=new URL(v.Representation?.BaseURL,m.data?.baseUri).toString(),L="internal",M=v.lang;T.push({id:D,url:V,type:L,language:M})}t.internalTextTracks.startTransitionTo(T)}}),this.subscription.add(Ye(this.video,t.isLooped,i));const{volumeState$:p,looped$:f,playbackRateState$:S,inPiP$:y,inFullscreen$:g,pause$:A,playing$:w}=Re(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:w,pause$:A,tracks$:this.videoTracks$.pipe(s.map(m=>m.map(({track:T})=>T)))}),this.subscription.add(Ce(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Ve(this.video,t.playbackRate,S,i)),this.subscription.add(y.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(N.STOPPED),k(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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=me(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,K.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(),i=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(i?.to!==exports.PlaybackState.PAUSED&&a.state===R.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:s.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:s.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:s.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),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case N.STOPPED:this.prepare();break;default:s.assertNever(e)}break}default:s.assertNever(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}xe(this.video),this.params.output.element$.next(void 0)}}var ft=r=>{switch(r){case"mobile":return s.VideoQuality.Q_144P;case"lowest":return s.VideoQuality.Q_240P;case"low":return s.VideoQuality.Q_360P;case"sd":case"medium":return s.VideoQuality.Q_480P;case"hd":case"high":return s.VideoQuality.Q_720P;case"fullhd":case"full":return s.VideoQuality.Q_1080P;case"quadhd":case"quad":return s.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return s.VideoQuality.Q_2160P}};const si=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Me=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!si(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return si(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function se(){return s.now()}function Di(r){return se()-r}function ai(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,c,d=!1)=>{a(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 ws(r,e,t){const i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function $t(r,e,t,i){const a=window.XMLHttpRequest;let n,o,c,d=!1,u=0,h,l,p=!1,f="arraybuffer",S=7e3,y=2e3,g=()=>{if(d)return;s.assertNonNullable(h);const I=Di(h);let j;if(I<y){j=y-I,setTimeout(g,j);return}y*=2,y>S&&(y=S),o&&o.abort(),o=new a,D()};const A=I=>(n=I,C),w=I=>(l=I,C),m=()=>(f="json",C),T=()=>{if(!d){if(--u>=0){g(),i&&i();return}d=!0,l&&l(),t&&t()}},v=I=>(p=I,C),D=()=>{h=se(),o=new a,o.open("get",r);let I=0,j,te=0;const ae=()=>(s.assertNonNullable(h),Math.max(h,Math.max(j||0,te||0)));if(n&&o.addEventListener("progress",P=>{const H=se();n.updateChunk&&P.loaded>I&&(n.updateChunk(ae(),P.loaded-I),I=P.loaded,j=H)}),c&&(o.timeout=c,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;s.assertNonNullable(o);const P=o.status;if(P>=200&&P<300){if(o.response.byteLength&&n){const H=o.response.byteLength-I;H&&n.updateChunk&&n.updateChunk(ae(),H)}l&&l(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),p){const P=()=>{s.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(te=se(),o.removeEventListener("readystatechange",P))};o.addEventListener("readystatechange",P)}return o.responseType=f,o.send(),C},C={withBitrateReporting:A,withParallel:v,withJSONResponse:m,withRetryCount:I=>(u=I,C),withRetryInterval:(I,j)=>(s.isNonNullable(I)&&(y=I),s.isNonNullable(j)&&(S=j),C),withTimeout:I=>(c=I,C),withFinally:w,send:D,abort:()=>{o&&(o.abort(),o=void 0),d=!0,l&&l()}};return C}const Ds=100,Cs=2e3,_s=500;let xs=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,i){return{start:e,end:t,bytes:i}}_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-_s;if(t-e>Cs){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,c=n.end-n.start;i+=o;const d=n.bytes*o/c;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>Ds&&(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 Rs{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,a,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,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 i=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()-i,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=$t(t,n,()=>a("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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,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}`),i(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=i,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 vt=1e4,Et=3,Ns=300,Ls=2e3,Is=6e4,Bs=10,Vs=1,Ms=500;class Fs{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 xs(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ai(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=ai(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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length;let a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,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)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{ws(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 Rs(Et,vt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,c=null,d=null,u=null,h=!1;const l=()=>{const T=n&&(!h||h===this.rep);return T||t("Not running!"),T},p=(T,v,D)=>{d&&d.abort(),d=$t(this.urlResolver.resolve(T,!1),v,D,()=>this._retryCallback()).withTimeout(vt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Et).withFinally(()=>{d=null}).send()},f=(T,v,D)=>{s.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),v,D,()=>this._retryCallback()).withFinally(()=>{c=null}).send()},S=T=>{const v=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${v}=>${T}`),i.playbackRate=T)},y=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const D=se()-1e4;let V=0;for(let M=0;M<this.bufferStates.length;M++){const E=this.bufferStates[M];T=Math.min(T,E.buf),E.ts<D&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${T} drop=${V} jitter=${this.sourceJitter}`);let L=T-Vs;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?S(1.15):L>1?S(1.1):L>.3?S(1.05):S(1)}},A=T=>{let v;const D=()=>v&&v.start?v.start.length:0,V=P=>v.start[P]/1e3,L=P=>v.dur[P]/1e3,M=P=>v.fragIndex+P,E=(P,H)=>({chunkIdx:M(P),startTS:V(P),dur:L(P),discontinuity:H}),C=()=>{let P=0;if(v&&v.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=H;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let oe=v.dur.length-1;for(;oe>=0&&(Z-=v.dur[oe],!(Z<=0));--oe);P=Math.min(oe,v.dur.length-1-J),P=Math.max(P,0)}return E(P,!0)},I=P=>{const H=D();if(!(H<=0)){if(s.isNonNullable(P)){for(let J=0;J<H;J++)if(V(J)>P)return E(J)}return C()}},j=P=>{const H=D(),J=P?P.chunkIdx+1:0,Z=J-v.fragIndex;if(!(H<=0)){if(!P||Z<0||Z-H>Bs)return t(`Resync: offset=${Z} bChunks=${H} chunk=`+JSON.stringify(P)),C();if(!(Z>=H))return E(J-v.fragIndex,!1)}},te=(P,H,J)=>{u&&u.abort(),u=$t(this.urlResolver.resolve(P,!0,this.lowLatency),H,J,()=>this._retryCallback()).withTimeout(vt).withRetryCount(Et).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,H)=>{te(T,J=>{if(!l())return;v=J;const Z=!!v.lowLatency;Z!==this.lowLatency&&y(Z);let oe=0;for(let Ne=0;Ne<v.dur.length;++Ne)oe+=v.dur[Ne];oe>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(oe/v.dur.length)),a({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,P(I(H))},()=>this._handleNetworkError())},nextChunk:j}},w=()=>{n=!1,c&&c.abort(),d&&d.abort(),u&&u.abort(),s.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:T=>{const{videoElement:v,logger:D}=this.params;let V=A(e.jidxUrl),L,M,E,C,I=0,j,te,ae;const P=()=>{j&&(clearTimeout(j),j=void 0);const U=Math.max(Ms,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=I+U,de=se(),ce=Math.min(1e4,re-de);I=de;const Fe=()=>{u||l()&&V.seek(()=>{l()&&(I=se(),H(),P())})};ce>0?j=window.setTimeout(()=>{this.paused?P():Fe()},ce):Fe()},H=()=>{let U;for(;U=V.nextChunk(C);)C=U,It(U);const re=V.nextChunk(E);if(re){if(E&&re.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?P():(w(),this._initPlayerWith(e));return}Ne(re)}else P()},J=(U,re)=>{if(!l()||!this.sourceBuffer)return;let de,ce,Fe;const pe=$e=>{window.setTimeout(()=>{l()&&J(U,re)},$e)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),pe(100);else{const $e=se(),be=v.currentTime;!this.paused&&v.buffered.length>1&&te===be&&$e-ae>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),te!==be&&(te=be,ae=$e);const Ae=this._getBufferSizeSec();if(Ae>30)D(`Buffered ${Ae} seconds; delaying appendBuffer`),pe(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:$e,buf:Ae}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(Ge){if(Ge.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(de=this.sourceBuffer.buffered.start(0),ce=be,ce-de>4&&this.sourceBuffer.remove(de,ce-3)),pe(1e3);else throw Ge}}},Z=()=>{M&&L&&(D([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(E)]),J(M,function(){M=null,H()}))},oe=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),Ne=U=>{l()&&f(oe(U),(re,de)=>{if(l()){if(de/=1e3,M=re,E=U,o=U.startTS,de){const ce=Math.min(10,U.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}Z()}},()=>this._handleNetworkError())},It=U=>{l()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(oe(U),!1)))},St=U=>{l()&&(e.cachedHeader=U,J(U,()=>{L=!0,Z()}))};n=!0,V.seek(U=>{if(l()){if(I=se(),!U){P();return}C=U,!s.isNullable(T)||U.startTS>T?Ne(U):(E=U,H())}},T),e.cachedHeader?St(e.cachedHeader):p(e.headerUrl,St,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>o},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),s.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,s.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return s.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,f,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),S=l/this.bitrate,f>10&&S>.8||f>15&&S>.5||f>20&&S>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},n=(()=>({updateChunk:(p,f)=>{const S=se();if(this.chunkRateEstimator.addInterval(p,S,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:S-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 l=n.get();if(l&&c&&this.autoQuality){if(d&&l>c&&Di(o)<3e4)return;i(l)}d=this.autoQuality};return{updateChunk:(l,p)=>{const f=n.updateChunk(l,p);return f&&u(),f},notifySwitch:l=>{const p=se();l<c&&(o=p),c=l}}}_fetchManifest(e,t,i){this.manifestRequest=$t(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(vt).withRetryCount(Et).withRetryInterval(Ns,Ls).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Me(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const c=[];return o?.length?(o.forEach((d,u)=>{d.video&&a.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}`),i({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))},Is))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var x;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(x||(x={}));const Os=[x.PAUSED,x.PLAYING,x.READY],Us=[x.PAUSED,x.PLAYING,x.READY];class Hs{subscription=new s.Subscription;video;videoState=new z(x.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new Ee;droppedFramesManager=new Rt;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new xt;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:s.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=_e(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.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ne(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 i=Re(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(s.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===x.READY&&this.videoState.setState(x.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===R.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(s.combine({zeroTime:this.zeroTime$.pipe(s.filter(s.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(Ye(this.video,this.params.desiredState.isLooped,t)).add(Ce(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ve(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{const n=a&&s.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(a.to)}},t)).add(s.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}createLiveDashPlayer(){const e=new Fs({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(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s.isNonNullable(t)?t:Ze(e.map(({track:d})=>d),{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(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((n&&a||a!==o)&&this.setVideoTrack(a),c&&this.setAutoQuality(i),n||c||a!==o){const d=e.find(({track:u})=>u.id===a)?.representation;s.assertNonNullable(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e)?.representation;s.assertNonNullable(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(me(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:s.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const a of t){const n=a.name??a.index.toString(10),o=ft(a.name)??s.videoSizeToQuality(a.video),c=a.bitrate/1e3,d={...a.video};if(!o)continue;const u={id:n,quality:o,bitrate:c,size:d};i.push({track:u,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),s.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=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: ${i}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(t)return;const o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Us.includes(e)&&(o||c)){this.prepare();return}if(a?.to!==exports.PlaybackState.PAUSED&&n.state===R.Requested&&Os.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(me(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const d=a?.from;d&&d===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)})}return;case x.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(x.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(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(me(this.params.source.url,d))}return;default:return s.assertNever(e)}}}var Ci=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?exports.HttpConnectionType.HTTP1:e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}},Be=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){const a=r.start(i)*1e3,n=r.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const js=r=>{const e=document.createElement("a");return e.href=r,e.origin},Ys=r=>{const e=document.createElement("a");return e.href=r,e.host};class _i{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,a,n,o){this._url=e,this._failoverHosts=t,this._completeCb=i,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(this._xhr){if(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(i=>i.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(Ys(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(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const a=this._sourceBuffer.buffered;let n=0;for(let o=0,c=a.length;o<c;o++)n+=a.end(o)-a.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,a,n,o,c){this.abort(()=>{let d=0;const u=Date.now();let h=0,l=0,p=0;const f=y=>{a(Pt._str2ua(y.substr(d))),d=y.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=Je(S)),this._lastXhr=new _i(S,e.failoverHosts,y=>{this._lastXhr=void 0,f(y);const g=Date.now()-u;this._params.onBandwidthChange({size:y.length,duration:g,speed:8*y.length/(g/1e3)}),this._onDashCallback("loading",{size:y.length,done:!0}),n?.()},y=>{if(y.length-d>c&&f(y),l===0){l=Date.now();return}p=y.length-h;const g=Date.now()-l;p>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:p,duration:g,speed:8*p/(g/1e3)}),p=0,h=y.length,l=Date.now()),this._onDashCallback("loading",{size:y.length,done:!1})},o,(y,g,A)=>this._params.onError(y,g,A))})}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(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};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 i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);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 Gs{_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)?)?$/,i=(c,d)=>{const u=c?parseFloat(c.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},a=t.exec(e),n=a?.[1]==="-"?-1:1,o={years:i(a?.[2],n),months:i(a?.[3],n),weeks:i(a?.[4],n),days:i(a?.[5],n),hours:i(a?.[6],n),minutes:i(a?.[7],n),seconds:i(a?.[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Je(i)),new _i(i,t,a=>{this.attachManifest(a,t,js(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,h)=>{const l=u.attributes.getNamedItem(h);return l?l.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const c=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{const h=u.getElementsByTagName("SegmentBase")[0],l=h&&o(h,"indexRange").split("-"),p=h&&h.getElementsByTagName("Initialization")[0],f=p&&o(p,"range").split("-");if(!f||!l){const m=u.parentElement;if(m?.getAttribute("contentType")==="text"){const T=u.getAttribute("id")??void 0,v=(i?i+"/":"")+u.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,D=m.getAttribute("lang")??void 0;v&&d.push({id:T,url:v,language:D})}return}const S=.1,y=Number(u.attributes.getNamedItem("bandwidth")?.value),g=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let A;const w=u.attributes.getNamedItem("frameRate")?.value??void 0;A=w?zt(w):void 0,c.push({width:Number(u.attributes.getNamedItem("width")?.value),height:Number(u.attributes.getNamedItem("height")?.value),bandwidth:y,baseURL:g,failoverHosts:t,indexFrom:Number(l[0]),indexTo:Number(l[1]),initFrom:Number(f[0]),initTo:Number(f[1]),codecs:u.attributes.getNamedItem("codecs")?.value??void 0,mimeType:u.attributes.getNamedItem("mimeType")?.value??void 0,fps:A,bufferSize:S*y/8,bufferLength:S,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:h,url:l})=>{const p=document.createElement("track");l&&p.setAttribute("src",l),u&&p.setAttribute("id",u),h&&p.setAttribute("srclang",h),this._video.appendChild(p)}),this._representations.sort((u,h)=>h.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=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 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 h=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let p=0;p<h;p+=1){const f=u+(o.getUint32(n,!1)&2147483647),S=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/c,toTime:S/c,fromOffset:u,toOffset:f-1}),u=f,d=S}const l=e.refs[e.refs.length-1];l.toTime-l.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,a=>{this._params.onResponseHeaders(a),this._params.onIdxRequestPing(Date.now()-i)},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 i=new t;let a,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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const h=this._appendVector[String(u.fromTime)];h!==a&&(a=h,this._params.onRepresentationPlay(h));let l;if(this._findRef(u.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}l=f.to-this._video.currentTime,l<e.bufferLength&&(this._onDashCallback("buffering"),n!==f.to&&(n=f.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(f);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},l*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=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Pt({mediaSource:i,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),i.duration||(i.duration=this._duration),this._loopTimeout||c(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),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,i=!1,a=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),c=Math.abs(this._video.currentTime-t),d=a||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 i=this._buffer.getByTime(this._video.currentTime),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(c,d)=>this._stream.remove(c,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(c,d)=>this._stream.remove(c,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||s.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 i;for(let a=0;a<t.length;a++){const n=t[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!i||n.fromTime<i.fromTime)&&(i=n)}if(!i){const a=t[t.length-1];if(e>a.toTime)return a}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var B;(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"})(B||(B={}));const qs=[B.PAUSED,B.PLAYING];class zs{videoState=new z(B.STOPPED);subscription=new s.Subscription;video;buffer;dash;representations$=new s.ValueSubject([]);currentRepresentation$=new s.ValueSubject(void 0);params;textTracksManager=new Ee;droppedFramesManager=new Rt;elementSize$=new s.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new s.Subject,responseHeaders$:new s.Subject,manifestReady$:new s.Subject,representationPlay$:new s.Subject,error$:new s.Subject};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),s.merge(this.videoState.stateChangeStarted$.pipe(s.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=_e(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(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ys(this.video),this.dash=new Gs({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:s.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,i=c=>{e.error$.next({id:"DashProvider",category:s.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:c})},a=()=>{const c=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:c},n=Re(this.video),o=(c,d)=>this.subscription.add(c.subscribe(d,i));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.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{s.isNullable(this.params.desiredState.seekState.getState().state!==R.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ye(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ve(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(s.map(c=>c.map(({track:d})=>d)))}),o(At(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(c=>{this.buffer.fill(),e.currentBuffer$.next(c)},i)).add(this.dashLiteEvents.error$.pipe(s.map(({id:c,message:d,thrown:u})=>({id:`DashLite_${c}`,category:s.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(s.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).pipe(s.map(()=>{const c=this.currentRepresentation$.getValue(),d=this.representations$.getValue(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState(),l=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),f=a();u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to);let S;if(!f&&s.isNonNullable(h))S=h;else{const y=Be(this.video.buffered,this.video.currentTime*1e3),g=f?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,A=Math.min(y/g,1);S=Ze(d.map(({track:m})=>m),{container:p,throughput:l,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:A,playbackRate:this.video.playbackRate,current:d.find(({representation:m})=>m===c)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const w=t.autoVideoTrackLimits.getTransition();w&&e.autoVideoTrackLimits$.next(w.to)}return s.isNonNullable(S)?d.find(({track:y})=>y.id===S)?.representation:void 0}),s.filterChanged()).subscribe(this.currentRepresentation$,i)).add(s.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(s.filter(c=>c.to===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(s.filter(s.isNonNullable))}).pipe(s.once()).subscribe(()=>this.videoState.setState(B.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(s.filter(s.isNonNullable),s.filterChanged((c,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?c.height<=d.height:c===d)).subscribe(c=>{const d=Be(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(c,!0),this.params.output.hostname$.next(ne(c.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(c=>{const{type:d,reused:u}=Ci(c);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(s.once(),s.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,i)).add(this.dashLiteEvents.representationPlay$.pipe(s.filter(s.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return s.assertNever(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const a of e){const n=a.name??a.id??a.height.toString(10),o=(a.name&&ft(a.name))??s.videoSizeToQuality(a),c=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!o)continue;const h={id:n,quality:o,bitrate:c,size:d,fps:u};i.push({track:h,representation:a})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),t?.length>0){const a=[];for(const n of t){const o=n.id||`${n.language}_${Date.now()}`;a.push({id:o,type:"internal",url:n.url||"",language:n.language,isAuto:n.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(a)}this.videoState.setState(B.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===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 s.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(){Me(this.video).then(e=>{e||(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.ErrorCategory.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=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: ${i}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(B.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(a?.to!==exports.PlaybackState.PAUSED&&n.state===R.Requested&&qs.includes(e)&&this.seek(n.position,n.forcePrecise),e){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}}var ee;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(ee||(ee={}));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 he;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(he||(he={}));var F;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(F||(F={}));var Xe;(function(r){r.MP4="mp4",r.WEBM="webm"})(Xe||(Xe={}));var Dt;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Dt||(Dt={}));var Q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Q||(Q={}));class ri{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];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 xi extends ri{constructor(){super(),this.listeners||ri.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 Ri=class{constructor(){Object.defineProperty(this,"signal",{value:new xi,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 i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ri.prototype[Symbol.toStringTag]="AbortController",xi.prototype[Symbol.toStringTag]="AbortSignal");function Ni(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 Qs(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!Ni({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,h){let l;h&&h.signal&&(l=h.signal,delete h.signal);const p=new t(u,h);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const h=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(h){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(h.aborted)return Promise.reject(l);const p=new Promise((f,S)=>{h.addEventListener("abort",()=>S(l),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,o(d,u)])}return o(d,u)},Request:n}}const Nt=Ni({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Li=Nt?Qs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Nt?Li.fetch:window.fetch;Nt?Li.Request:window.Request;const We=Nt?Ri:window.AbortController;var jt=(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 Ws=(r,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Js=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ni=Js?Ws:window.requestIdleCallback;let Ii=!1;try{Ii=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class Xs{bufferFull$=new s.Subject;error$=new s.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(i=>{const a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Ii&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:s.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:s.assertNever(t)}}}var oi=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};class ke{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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Bi extends ke{}class Ks extends ke{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 i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Zs extends ke{parseChildrenBoxes(){return et(this.content)}}class ea extends ke{data;constructor(e){super(e),this.data=this.content}}class mt extends ke{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class ta extends mt{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 i=this.readUint32();const a=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const c=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:d})}}}class ia extends ke{parseChildrenBoxes(){return et(this.content)}}class sa extends ke{parseChildrenBoxes(){return et(this.content)}}var je;(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"})(je||(je={}));class aa extends mt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=je.MONOSCOPIC;break;case 1:this.stereoMode=je.TOP_BOTTOM;break;case 2:this.stereoMode=je.LEFT_RIGHT;break;case 3:this.stereoMode=je.STEREO_CUSTOM;break;case 4:this.stereoMode=je.RIGHT_LEFT;break}this.cursor+=1}}class ra extends mt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class na extends mt{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 oa extends ke{parseChildrenBoxes(){return et(this.content)}}class ca extends mt{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 ua extends ke{parseChildrenBoxes(){return et(this.content)}}class da extends ke{parseChildrenBoxes(){return et(this.content)}}const la={ftyp:Ks,moov:Zs,mdat:ea,sidx:ta,trak:ia,mdia:oa,tkhd:ca,minf:ua,sv3d:sa,st3d:aa,prhd:ra,proj:da,equi:na,unknown:Bi};class ha{createBox(e,t){const i=la[e];return i?new i(t):new Bi(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Lt.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Lt=new ha;function ut(r,e){const t=new TextDecoder("ascii");let i=r.byteOffset,a=[];for(;i<r.byteLength;){const n=t.decode(new DataView(r.buffer,i,1));if(n===e[a.length]?a.push(n):a=[],a.length===4&&a.join("")===e){const c=new DataView(r.buffer,i-7,4).getUint32(0);return i-7+c>r.byteLength?null:Lt.createBox(e,new DataView(r.buffer,i-7))}i++}return null}function pa(r,e){const t=[];let i=0;for(;i<r.byteLength;){const a=ut(new DataView(r.buffer,r.byteOffset+i,r.byteLength-i),e);if(a)t.push(a),i+=a.size+a.source.byteOffset;else break}return t}function et(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Lt.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const fa=new TextDecoder("ascii"),ma=r=>fa.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Sa=r=>{const e=Lt.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=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:F.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,c})},ba=r=>{const e=pa(r,"mdat");if(e.length){const t=e.reduce((i,a)=>i+a.size,0);return new DataView(r.buffer,r.byteOffset,t)}return null},ga=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Dt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ut(r,"sv3d")){e.is3dVideo=!0;const i=ut(r,"st3d");i&&(e.stereoMode=i.stereoMode);const a=ut(r,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=ut(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},ya={validateData:ma,parseInit:ga,getIndexRange:()=>{},parseSegments:Sa,parseFeedableSegmentChunk:ba};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 $;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})($||($={}));const ci={[b.EBML]:{type:$.Master},[b.EBMLVersion]:{type:$.UnsignedInteger},[b.EBMLReadVersion]:{type:$.UnsignedInteger},[b.EBMLMaxIDLength]:{type:$.UnsignedInteger},[b.EBMLMaxSizeLength]:{type:$.UnsignedInteger},[b.DocType]:{type:$.String},[b.DocTypeVersion]:{type:$.UnsignedInteger},[b.DocTypeReadVersion]:{type:$.UnsignedInteger},[b.Void]:{type:$.Binary},[b.Segment]:{type:$.Master},[b.SeekHead]:{type:$.Master},[b.Seek]:{type:$.Master},[b.SeekID]:{type:$.Binary},[b.SeekPosition]:{type:$.UnsignedInteger},[b.Info]:{type:$.Master},[b.TimestampScale]:{type:$.UnsignedInteger},[b.Duration]:{type:$.Float},[b.Tracks]:{type:$.Master},[b.TrackEntry]:{type:$.Master},[b.Video]:{type:$.Master},[b.Projection]:{type:$.Master},[b.ProjectionType]:{type:$.UnsignedInteger},[b.ProjectionPrivate]:{type:$.Master},[b.Chapters]:{type:$.Master},[b.Cluster]:{type:$.Master},[b.Timestamp]:{type:$.UnsignedInteger},[b.SilentTracks]:{type:$.Master},[b.SilentTrackNumber]:{type:$.UnsignedInteger},[b.Position]:{type:$.UnsignedInteger},[b.PrevSize]:{type:$.UnsignedInteger},[b.SimpleBlock]:{type:$.Binary},[b.BlockGroup]:{type:$.Master},[b.EncryptedBlock]:{type:$.Binary},[b.Attachments]:{type:$.Master},[b.Tags]:{type:$.Master},[b.Cues]:{type:$.Master},[b.CuePoint]:{type:$.Master},[b.CueTime]:{type:$.UnsignedInteger},[b.CueTrackPositions]:{type:$.Master},[b.CueTrack]:{type:$.UnsignedInteger},[b.CueClusterPosition]:{type:$.UnsignedInteger},[b.CueRelativePosition]:{type:$.UnsignedInteger},[b.CueDuration]:{type:$.UnsignedInteger},[b.CueBlockNumber]:{type:$.UnsignedInteger},[b.CueCodecState]:{type:$.UnsignedInteger},[b.CueReference]:{type:$.Master},[b.CueRefTime]:{type:$.UnsignedInteger}},Vi=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 i=Ct(r,t),a=i in ci,n=a?ci[i].type:$.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,h=Ct(d),l=u*2**((c-1)*8)+h,p=t+c;let f;return p+l>r.byteLength?f=new DataView(r.buffer,r.byteOffset+p):f=new DataView(r.buffer,r.byteOffset+p,l),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:p,tagSize:p+l,value:f,valueSize:l}},Ct=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Te=(r,e)=>{switch(e){case $.SignedInteger:return r.getInt8(0);case $.UnsignedInteger:return Ct(r);case $.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case $.String:return new TextDecoder("ascii").decode(r);case $.UTF8:return new TextDecoder("utf-8").decode(r);case $.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case $.Master:return r;case $.Binary:return r;default:s.assertNever(e)}},Ke=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),a=Vi(i);if(!e(a))return;a.type===$.Master&&Ke(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},Ta=r=>{if(r.getUint32(0)!==b.EBML)return!1;let e,t,i;const a=Vi(r);return Ke(a.value,({tag:n,type:o,value:c})=>(n===b.EBMLReadVersion?e=Te(c,o):n===b.DocType?t=Te(c,o):n===b.DocTypeReadVersion&&(i=Te(c,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Mi=[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],va=[b.Timestamp,b.SilentTracks,b.SilentTrackNumber,b.Position,b.PrevSize,b.SimpleBlock,b.BlockGroup,b.EncryptedBlock],Ea=r=>{let e,t,i,a,n=!1,o=!1,c=!1,d,u,h=!1;const l=0;return Ke(r,({tag:p,type:f,value:S,valueSize:y})=>{if(p===b.SeekID){const g=Te(S,f);u=Ct(g)}else p!==b.SeekPosition&&(u=void 0);return p===b.Segment?(e=S.byteOffset,t=S.byteOffset+y):p===b.Info?n=!0:p===b.SeekHead?o=!0:p===b.TimestampScale?i=Te(S,f):p===b.Duration?a=Te(S,f):p===b.SeekPosition&&u===b.Cues?d=Te(S,f):p===b.Tracks?Ke(S,({tag:g,type:A,value:w})=>g===b.ProjectionType?(h=Te(w,A)===1,!1):!0):n&&o&&Mi.includes(p)&&(c=!0),!c}),s.assertNonNullable(e,"Failed to parse webm Segment start"),s.assertNonNullable(t,"Failed to parse webm Segment end"),s.assertNonNullable(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:Dt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ka=r=>{if(s.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},$a=(r,e)=>{let t=!1,i=!1;const a=c=>s.isNonNullable(c.time)&&s.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&&a(o)&&n.push(o),o={};break;case b.CueTime:o&&(o.time=Te(u,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:o&&(o.position=Te(u,d));break;default:t&&Mi.includes(c)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((c,d)=>{const{time:u,position:h}=c,l=n[d+1];return{status:F.NONE,time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},Aa=r=>{let e=0,t=!1;try{Ke(r,i=>i.tag===b.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):va.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[b.SimpleBlock,b.BlockGroup,b.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Pa={validateData:Ta,parseInit:Ea,getIndexRange:ka,parseSegments:$a,parseFeedableSegmentChunk:Aa},Fi=1e4,wa=3e4,Da=5e3,Ca=Fi,_a=({id:r,width:e,height:t,bitrate:i,fps:a,quality:n})=>{const o=(n?ft(n):void 0)??s.videoSizeToQuality({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a}},xa=({id:r,bitrate:e})=>({id:r,bitrate:e}),Ra=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},Na=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),kt=r=>{const e=[];let t=0,i=r.length-1;for(;t<Fi&&i>=0;)e.unshift(r[i]),t+=r[i].time.to-r[i].time.from,i--;return e};class ui{onLastSegment$=new s.ValueSubject(!1);fullyBuffered$=new s.ValueSubject(!1);playingRepresentation$=new s.ValueSubject(void 0);playingRepresentationInit$=new s.ValueSubject(void 0);error$=new s.Subject;gaps=[];isSeekingLive=!1;subscription=new s.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new We;destroyAbortController=new We;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:c,compatibilityMode:d=!1,manifest:u}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=c,this.isLive=!!u?.dynamic,this.container=i,i){case Xe.MP4:this.containerParser=ya;break;case Xe.WEBM:this.containerParser=Pa;break;default:s.assertNever(i)}this.initData=new Map(a.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=s.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);s.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 Xs(this.sourceBuffer),this.subscription.add(s.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:s.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(s.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:s.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const c=Math.min(this.bufferLimit,oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=c,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),a=this.segments.get(t.id),n=this.parsedInitData.get(t.id);s.assertNonNullable(i,"No init buffer for starting representation"),s.assertNonNullable(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=s.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);s.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),a=this.initData.get(e);if(s.isNullable(a)||s.isNullable(i)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),i=this.segments.get(e),s.assertNonNullable(i,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);const n=this.getCurrentPosition();s.isNonNullable(n)&&(this.searchGaps(i,t),this.maintain(n))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new We,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(s.isNullable(e)||s.isNullable(this.downloadingRepresentationId)||s.isNullable(this.playingRepresentationId)||s.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(s.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Be(this.sourceBuffer.buffered,e),l=a?a.time.to+100:-1/0;a&&h>=a.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&oi(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Be(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<h);return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(i,t.segmentReference.type,n),c.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(c.includes(a))u="high";else{const h=c.at(0);h&&h.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(c,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===F.FED&&!c.length&&Be(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=i.at(-1);d&&d.status===F.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const a of e)a.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from}),i=a.time.to;s.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=s.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const c of this.representations.keys()){const d=e.find(l=>l.id===c);d&&this.representations.set(c,d);const u=this.representations.get(c);if(!u)return;const h=kt(u.segmentReference.segments);this.segments.set(u.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);s.assertNonNullable(i);const a=kt(i.segmentReference.segments),n=this.initData.get(i.id);if(s.assertNonNullable(n,"No init buffer for starting representation"),s.assertNonNullable(a,"No segments for starting representation"),!(n instanceof ArrayBuffer))return;const o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t)return;const i=t.segmentReference.segments.map(c=>({...c,status:F.NONE,size:void 0})),a=this.segments.get(t.id)??[],n=a.at(-1)?.time.to??0,o=i?.findIndex(c=>Math.round(n)>=Math.round(c.time.from)&&Math.round(n)<=Math.round(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const c=kt(i);this.segments.set(t.id,[...c])}else{const c=i.slice(o+1);this.segments.set(t.id,[...a,...c])}}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(n=>n.time.from<=e&&n.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.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();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const a=e.findIndex(({status:l,time:{from:p,to:f}},S)=>{const y=p<=i&&f>=i,g=p>i||y||S===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&p<=i+A||f<=i+A;return(l===F.NONE||l===F.PARTIALLY_EJECTED&&g&&w&&this.sourceBuffer&&!jt(this.sourceBuffer.buffered,i))&&g&&w});if(a===-1)return[];if(t!==he.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,c=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=a;l<n.length&&(o<=u||c<=h);l++){const p=n[l];if(o+=p.byte.to+1-p.byte.from,c+=p.time.to+1-p.time.from,p.status===F.NONE||p.status===F.PARTIALLY_EJECTED)d.push(p);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:c}=t.segmentReference;switch(c){case he.BYTE_RANGE:{a=t.segmentReference.url,n={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case he.TEMPLATE:{const u=e.at(0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:s.assertNever(c)}for(const u of o)u.status=F.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await s.abortable(d,async function*(){const u=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,u))}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(a,{range:n,onProgress:(u,h)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,h,d)}catch(l){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:d,priority:i}).then(()=>this.failedDownloads=0,u=>{if(u.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(u)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&s.isNonNullable(i)&&(t=Be(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:s.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},c=l=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),l.segment.status=F.FED,"size"in l.segment&&(l.segment.size=l.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const f of this.segments.get(p.id)??[])f.status===F.FED&&f.time.from===l.segment.time.from&&f.time.to===l.segment.time.to&&(f.status=F.NONE);this.activeSegments.delete(l),this.detectGapsWhenIdle(t,[l.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,h=e.byteLength;for(const l of this.activeSegments){const{segment:p}=l,f=u===he.BYTE_RANGE,S=f?p.byte.to-p.byte.from+1:h;if(l.representationId!==t||!(!f||p.byte.from>=i&&p.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const g=f?p.byte.from-i:0,A=f?p.byte.to-i:e.byteLength,w=g<a,m=A<=a;if(p.status===F.DOWNLOADING&&w&&m){p.status=F.DOWNLOADED,this.activeSegments.delete(l);const T=new DataView(e.buffer,e.byteOffset+g,S);this.sourceBufferTaskQueue.append(T,n).then(v=>v&&!n.aborted?c(l):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&w&&(l.loadedBytes=Math.min(S,a-g),l.loadedBytes>l.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+g+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===S?T:this.containerParser.parseFeedableSegmentChunk(T);v?.byteLength&&(p.status=F.PARTIALLY_FED,l.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,n).then(D=>{if(n.aborted)o();else if(D)l.fedBytes+=v.byteLength,l.fedBytes===S&&c(l);else{if(l.feedingBytes<S)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===F.PARTIALLY_FED||e.status===F.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=F.NONE),e.status=F.PARTIALLY_EJECTED):e.status=F.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=ni(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?s.abortable(this.destroyAbortController.signal,async function*(){const c=s.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,a)).then(async c=>{if(!c)return;const{init:d,dataView:u,segments:h}=c,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,this.isLive?kt(h):h),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,c=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:s.ErrorCategory.WTF,message:"loadInit threw",thrown:c})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||s.isNullable(e)||this.sourceBuffer.updating)return!1;let a=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 h="size"in u?u.size??0:u.byte.to-u.byte.from;a+=h};for(const u of this.segments.values())for(const h of u){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;h.status===F.FED&&d(h)}if(c=isFinite(n)&&isFinite(o),!c){a=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const h of u){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;h.status===F.FED&&d(h)}}if(c=isFinite(n)&&isFinite(o),!c)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const h=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===F.NONE&&Math.round(f.time.from)<=Math.round(h)&&Math.round(f.time.to)>=Math.round(l)){n=h,o=l;break}}if(c=isFinite(n)&&isFinite(o),!c&&i){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+u&&l.status===F.FED&&d(l)}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)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&c>=i.time.to){a=void 0;break}c>i.time.from&&c<i.time.to&&(a.from=c),o<i.time.to&&o>i.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=ni(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:s.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(s.isNullable(this.sourceBuffer)||s.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==F.FED&&n!==F.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),c=Math.ceil(a.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=c),u=e.filter(h=>o>=h.from-t&&o<=h.to+t||c>=h.from-t&&c<=h.to+t);d||(u.length===1?a.status=F.PARTIALLY_EJECTED:a.status=F.NONE)}}}var Qe;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Qe||(Qe={}));class La{throughputEstimator;requestQuic;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);abortAllController=new We;subscription=new s.Subscription;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Ci(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=s.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Je(t));const i=yield ht(t,{signal:this.abortAllController.signal}).catch(nt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=s.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Qe.HEADER:Qe.PARAM,range:i,onProgress:a,priority:n="auto",signal:o,measureThroughput:c=!0}={}){let d=e;const u=new Headers;if(i)switch(t){case Qe.HEADER:{u.append("Range",`bytes=${i.from}-${i.to}`);break}case Qe.PARAM:{const E=new URL(d,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),d=E.toString();break}default:s.assertNever(t)}this.requestQuic&&(d=Je(d));let h=this.abortAllController.signal,l;if(o){const E=new We;if(l=s.merge(s.fromEvent(this.abortAllController.signal,"abort"),s.fromEvent(o,"abort")).subscribe(()=>{try{E.abort()}catch(C){nt(C)}}),this.abortAllController.signal.aborted||o.aborted)try{E.abort()}catch(C){nt(C)}h=E.signal}const p=s.now(),f=yield ht(d,{priority:n,headers:u,signal:h}).catch(nt),S=s.now();if(this.throughputEstimator?.addRawRtt(S-p),!f)return l?.unsubscribe(),null;if(!f.ok||!f.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const y=parseInt(f.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!y){const E=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(E.byteLength,s.now()-S),a?.(new DataView(E),E.byteLength),l?.unsubscribe(),E}if(!a&&!c)return l?.unsubscribe(),f.arrayBuffer();const[g,A]=f.body.tee(),w=g.getReader();c&&this.throughputEstimator?.trackStream(A);let m=0;const T=new ArrayBuffer(y),v=new Uint8Array(T),D=new DataView(T);let V=!1;const L=E=>{l?.unsubscribe(),V=!0,nt(E)},M=s.abortable(h,async function*({done:E,value:C}){if(m===0&&this.lastRequestFirstBytes$.next(s.now()-p),h.aborted){l?.unsubscribe();return}!E&&C&&(v.set(C,m),m+=C.byteLength,a?.(D,m),yield w?.read().then(M,L))}.bind(this));return yield w?.read().then(M,L),l?.unsubscribe(),V?null:T}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:a}=e;switch(a){case he.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case he.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:s.assertNever(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==he.BYTE_RANGE)return null;const{from:a,to:n}=e.initRange;let o=a,c=n,d=!1,u,h;e.indexRange&&(u=e.indexRange.from,h=e.indexRange.to,d=n+1===u,d&&(o=Math.min(u,a),c=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:c},priority:i,measureThroughput:!1});if(!l)return null;const p=new DataView(l,a-o,n-o+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),S=e.indexRange??t.getIndexRange(f);if(!S)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,S.from-o,S.to-S.from+1);else{const A=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!A)return null;y=new DataView(A)}const g=t.parseSegments(y,f,S);return{init:f,dataView:new DataView(l),segments:g}}.bind(this));fetchTemplateRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==he.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(o=>({...o,status:F.NONE,size:void 0})),dataView:new DataView(a)}:null}.bind(this))}const nt=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},di=r=>{if(!r.startsWith("P"))return;const e=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,n={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Ft=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(c,d)=>s.isNullable(n)?c:s.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Ia=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],c=o.children,d=n.getAttribute("type")==="dynamic",u=n.getAttribute("availabilityStartTime"),h=u?new Date(u).getTime():void 0;let l;const p=n.getAttribute("mediaPresentationDuration"),f=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)l=di(p);else if(f){const m=di(f);s.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let g=0;const A=n.getAttribute("profiles")?.split(",")??[],w=A.includes(wt.WEBM_AS_IN_FFMPEG)||A.includes(wt.WEBM_AS_IN_SPEC)?Xe.WEBM:Xe.MP4;for(const m of c){const T=m.getAttribute("mimeType"),v=m.getAttribute("codecs"),D=m.getAttribute("contentType")??T?.split("/")[0],V=m.getAttribute("profiles")?.split(",")??[],L=m.querySelectorAll("Representation"),M=m.querySelector("SegmentTemplate");if(D===ee.TEXT){for(const E of L){const C=E.getAttribute("id")||"",I=m.getAttribute("lang"),j=E.querySelector("BaseURL")?.textContent?.trim()??"",te=new URL(j,e).toString(),ae=C.includes("_auto");a[ee.TEXT].push({id:C,lang:I,isAuto:ae,kind:ee.TEXT,url:te})}continue}for(const E of L){const C=E.getAttribute("mimeType")??T,I=E.getAttribute("codecs")??v??"",j=E.getAttribute("contentType")??C?.split("/")[0]??D,te=m.getAttribute("profiles")?.split(",")??[],ae=parseInt(E.getAttribute("width")??"",10),P=parseInt(E.getAttribute("height")??"",10),H=parseInt(E.getAttribute("bandwidth")??"",10)/1e3,J=E.getAttribute("frameRate")??"",Z=E.getAttribute("quality")??void 0,oe=J?zt(J):void 0,Ne=E.getAttribute("id")??(g++).toString(10),It=j==="video"?`${P}p`:j==="audio"?`${H}Kbps`:I,St=`${Ne}@${It}`,U=E.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(U,e).toString(),de=[...A,...V,...te];let ce;const Fe=E.querySelector("SegmentBase"),pe=E.querySelector("SegmentTemplate")??M;if(Fe){const be=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ae,Ge]=be.split("-").map(qe=>parseInt(qe,10)),tt={from:Ae,to:Ge},it=E.querySelector("SegmentBase")?.getAttribute("indexRange"),[Bt,bt]=it?it.split("-").map(qe=>parseInt(qe,10)):[],st=it?{from:Bt,to:bt}:void 0;ce={type:he.BYTE_RANGE,url:re,initRange:tt,indexRange:st}}else if(pe){const be={representationId:E.getAttribute("id")??void 0,bandwidth:E.getAttribute("bandwidth")??void 0},Ae=parseInt(pe.getAttribute("timescale")??"",10),Ge=pe.getAttribute("initialization")??"",tt=pe.getAttribute("media"),it=parseInt(pe.getAttribute("startNumber")??"",10)??1,Bt=Ft(Ge,be);if(!tt)throw new ReferenceError("No media attribute in SegmentTemplate");const bt=pe.querySelectorAll("SegmentTimeline S")??[],st=[];let qe=0;if(bt.length){let Vt=it,Pe=0;for(const at of bt){const Le=parseInt(at.getAttribute("d")??"",10),Oe=parseInt(at.getAttribute("r")??"",10)||0,gt=parseInt(at.getAttribute("t")??"",10);Pe=Number.isFinite(gt)?gt:Pe;const Mt=Le/Ae*1e3,Wt=Pe/Ae*1e3;for(let yt=0;yt<Oe+1;yt++){const zi=Ft(tt,{...be,segmentNumber:Vt.toString(10),segmentTime:(Pe+yt*Le).toString(10)}),Jt=(Wt||0)+yt*Mt,Qi=Jt+Mt;Vt++,st.push({time:{from:Jt,to:Qi},url:zi})}Pe+=(Oe+1)*Le,qe+=(Oe+1)*Mt}}else if(s.isNonNullable(l)){const Pe=parseInt(pe.getAttribute("duration")??"",10)/Ae*1e3,at=Math.ceil(l/Pe);let Le=0;for(let Oe=1;Oe<at;Oe++){const gt=Ft(tt,{...be,segmentNumber:Oe.toString(10),segmentTime:Le.toString(10)});st.push({time:{from:Le,to:Le+Pe},url:gt}),Le+=Pe}}ce={type:he.TEMPLATE,baseUrl:re,initUrl:Bt,totalSegmentsDurationMs:qe,segments:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!C)continue;const $e={video:ee.VIDEO,audio:ee.AUDIO,text:ee.TEXT}[j];$e&&a[$e].push({id:St,kind:$e,segmentReference:ce,profiles:de,duration:l,bitrate:H,mime:C,codecs:I,width:ae,height:P,fps:oe,quality:Z})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:w,representations:a}},Yt=1e3,li=["timeupdate","progress","play","seeked","stalled","waiting"];var le;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(le||(le={}));let Ba=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new s.Subscription;representationSubscription=new s.Subscription;fetcher;state$=new z(le.NONE);currentVideoRepresentation$=new s.ValueSubject(void 0);currentVideoRepresentationInit$=new s.ValueSubject(void 0);error$=new s.Subject;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);isLive$=new s.ValueSubject(!1);liveDuration$=new s.ValueSubject(0);liveAvailabilityStartTime$=new s.ValueSubject(void 0);bufferLength$=new s.ValueSubject(0);liveLoadBufferLength$=new s.ValueSubject(0);forceEnded$=new s.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new We;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new La({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=s.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=me(t,i,K.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:s.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=s.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:s.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return this.manifest;let t;try{t=Ia(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:s.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;const i=({kind:a,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||a===ee.TEXT);return this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([a,n])=>[a,n.filter(i)]))}}.bind(this));async seekLive(e){s.assertNonNullable(this.element),this.manifestUrlString=me(this.manifestUrlString,e,K.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=s.abortable(this.destroyController.signal,async function*(e,t){s.assertNonNullable(this.manifest),s.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(le.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new ui(ee.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s.isNonNullable(t)&&(this.audioBufferManager=new ui(ee.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(s.interval(Yt).subscribe(o=>{if(this.element?.paused){const c=Zt(this.manifestUrlString,K.DASH_CMAF_OFFSET_P);this.manifestUrlString=me(this.manifestUrlString,c+1e3,K.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(s.merge(...li.map(o=>s.fromEvent(this.element,o))).pipe(s.throttle(Yt),s.map(o=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(c=>{let d=0;if(c){const u=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-u}this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async c=>{s.assertNonNullable(this.element);const d=this.element.playbackRate,u=Zt(this.manifestUrlString,K.DASH_CMAF_OFFSET_P),h=wa*d,l=Ca*d,p=Da*d;o=c>o?c:o;const f=u===0&&c<p,S=u!==0&&c<h+p&&c>=h,y=u!==0&&c<h;if(y||S){const g=o-(h+l),A=Math.trunc(u+g/d);let w;c?A>0?w=A:w=0:w=u,this.manifestUrlString=me(this.manifestUrlString,w,K.DASH_CMAF_OFFSET_P)}(f||y||S)&&(await this.updateLive(),o=0)}))}const a=s.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(s.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=s.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(s.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(s.merge(this.forceEnded$,s.combine({allBuffersFull:a,someBufferEnded:n}).pipe(s.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:s.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(s.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.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))),s.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){s.assertNonNullable(this.element),this.state$.setState(le.RUNNING),this.subscription.add(s.merge(...li.map(e=>s.fromEvent(this.element,e)),s.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:s.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(s.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(s.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[ee.VIDEO]:this.videoBufferManager,[ee.AUDIO]:this.audioBufferManager,[ee.TEXT]:null}[e]?.switchTo(t)}seek(e,t){s.assertNonNullable(this.element),s.assertNonNullable(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),jt(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(le.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.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=s.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:s.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const a=Math.max(...i);a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class Va{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Ma{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const a=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var Fa=`#define GLSLIFY 1
|
|
30
30
|
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,Oa=`#ifdef GL_ES
|
|
31
31
|
precision highp float;precision highp int;
|
|
32
32
|
#else
|