@vkontakte/videoplayer-core 2.0.92 → 2.0.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.92
3
- * Thu, 16 Nov 2023 17:30:22 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-92/doc/
2
+ * @vkontakte/videoplayer-core v2.0.93
3
+ * Fri, 17 Nov 2023 13:52:44 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-93/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.92";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 x;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(x||(x={}));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 ve=(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===x.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:x.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=ve(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===x.Applying||i.state===x.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===x.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===x.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 me=(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)=>me(e,()=>r.loop,i=>{s.isNonNullable(i)&&(r.loop=i)},{onError:t}),Ce=(r,e,t,i)=>me(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)=>me(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(me(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(me(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(me(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(me(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){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},Re=r=>{const e=Ut.get(r);Ut.delete(r),e?qt(r):Ss(r)};class Rt{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 xe=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 ge{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 ge("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.93";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 x;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(x||(x={}));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 ve=(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===x.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:x.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=ve(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===x.Applying||i.state===x.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===x.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===x.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 me=(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)=>me(e,()=>r.loop,i=>{s.isNonNullable(i)&&(r.loop=i)},{onError:t}),Ce=(r,e,t,i)=>me(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)=>me(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(me(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(me(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(me(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(me(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){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},Re=r=>{const e=Ut.get(r);Ut.delete(r),e?qt(r):Ss(r)};class Rt{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 xe=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 ge{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 ge("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 re=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 xt{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 xt;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 Rt;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(re(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(me(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(me(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(re(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 ue={id:E,quality:C,bitrate:I,size:j,fps:te};D.push({track:ue,bitrateInfo:M}),M.qualityIndex===V&&(L=ue)}}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}=xe(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=ve(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===x.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{}Re(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 ue=()=>(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(ue(),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(ue(),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 Rs=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 xs{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 Rs(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 xs(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 ne=v.dur.length-1;for(;ne>=0&&(Z-=v.dur[ne],!(Z<=0));--ne);P=Math.min(ne,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 ne=0;for(let Ne=0;Ne<v.dur.length;++Ne)ne+=v.dur[Ne];ne>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ne/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,ue;const P=()=>{j&&(clearTimeout(j),j=void 0);const U=Math.max(Ms,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=I+U,de=se(),oe=Math.min(1e4,ae-de);I=de;const Fe=()=>{u||l()&&V.seek(()=>{l()&&(I=se(),H(),P())})};oe>0?j=window.setTimeout(()=>{this.paused?P():Fe()},oe):Fe()},H=()=>{let U;for(;U=V.nextChunk(C);)C=U,It(U);const ae=V.nextChunk(E);if(ae){if(E&&ae.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?P():(w(),this._initPlayerWith(e));return}Ne(ae)}else P()},J=(U,ae)=>{if(!l()||!this.sourceBuffer)return;let de,oe,Fe;const pe=$e=>{window.setTimeout(()=>{l()&&J(U,ae)},$e)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),pe(100);else{const $e=se(),Se=v.currentTime;!this.paused&&v.buffered.length>1&&te===Se&&$e-ue>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),te!==Se&&(te=Se,ue=$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()),ae&&ae()}catch(Ge){if(Ge.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(de=this.sourceBuffer.buffered.start(0),oe=Se,oe-de>4&&this.sourceBuffer.remove(de,oe-3)),pe(1e3);else throw Ge}}},Z=()=>{M&&L&&(D([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(E)]),J(M,function(){M=null,H()}))},ne=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),Ne=U=>{l()&&f(ne(U),(ae,de)=>{if(l()){if(de/=1e3,M=ae,E=U,o=U.startTS,de){const oe=Math.min(10,U.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*oe:oe}Z()}},()=>this._handleNetworkError())},It=U=>{l()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ne(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 R;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(R||(R={}));const Os=[R.PAUSED,R.PLAYING,R.READY],Us=[R.PAUSED,R.PLAYING,R.READY];class Hs{subscription=new s.Subscription;video;videoState=new z(R.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new Ee;droppedFramesManager=new xt;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new Rt;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(re(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=xe(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===R.READY&&this.videoState.setState(R.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(R.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===x.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(R.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 R.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case R.MANIFEST_READY:case R.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case R.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case R.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return 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),Re(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===R.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ve(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===R.MANIFEST_READY&&this.videoState.setState(R.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!==R.STOPPED&&(this.videoState.startTransitionTo(R.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(R.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===x.Requested&&Os.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case R.STOPPED:this.videoState.startTransitionTo(R.MANIFEST_READY),this.dash.attachSource(ve(this.params.source.url));return;case R.MANIFEST_READY:this.videoState.startTransitionTo(R.READY),this.prepare();break;case R.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(R.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(R.PLAYING);const d=a?.from;d&&d===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(R.PAUSED)})}return;case R.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(R.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case R.PAUSED:i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(R.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(R.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return 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 xt;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(re(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=xe(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!==x.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(re(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),Re(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===x.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 Ri 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 xi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ri,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&&(xi.prototype[Symbol.toStringTag]="AbortController",Ri.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?xi: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},ye=(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=ye(c,o):n===b.DocType?t=ye(c,o):n===b.DocTypeReadVersion&&(i=ye(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=ye(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=ye(S,f):p===b.Duration?a=ye(S,f):p===b.SeekPosition&&u===b.Cues?d=ye(S,f):p===b.Tracks?Ke(S,({tag:g,type:A,value:w})=>g===b.ProjectionType?(h=ye(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=ye(u,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:o&&(o.position=ye(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}},Ra=({id:r,bitrate:e})=>({id:r,bitrate:e}),xa=(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();a[ee.TEXT].push({id:C,lang:I,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(",")??[],ue=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,ne=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()??"",ae=new URL(U,e).toString(),de=[...A,...V,...te];let oe;const Fe=E.querySelector("SegmentBase"),pe=E.querySelector("SegmentTemplate")??M;if(Fe){const Se=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ae,Ge]=Se.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;oe={type:he.BYTE_RANGE,url:ae,initRange:tt,indexRange:st}}else if(pe){const Se={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,Se);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,{...Se,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,{...Se,segmentNumber:Oe.toString(10),segmentTime:Le.toString(10)});st.push({time:{from:Le,to:Le+Pe},url:gt}),Le+=Pe}}oe={type:he.TEMPLATE,baseUrl:ae,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:oe,profiles:de,duration:l,bitrate:H,mime:C,codecs:I,width:ue,height:P,fps:ne,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=ve(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=ve(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=ve(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=ve(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 xt{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 xt;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 Rt;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(me(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(me(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}=xe(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=ve(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===x.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{}Re(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 Rs=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 xs{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 Rs(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 xs(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(),Se=v.currentTime;!this.paused&&v.buffered.length>1&&te===Se&&$e-ae>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),te!==Se&&(te=Se,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=Se,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 R;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(R||(R={}));const Os=[R.PAUSED,R.PLAYING,R.READY],Us=[R.PAUSED,R.PLAYING,R.READY];class Hs{subscription=new s.Subscription;video;videoState=new z(R.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new Ee;droppedFramesManager=new xt;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new Rt;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=xe(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===R.READY&&this.videoState.setState(R.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(R.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===x.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(R.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 R.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case R.MANIFEST_READY:case R.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case R.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case R.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return 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),Re(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===R.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ve(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===R.MANIFEST_READY&&this.videoState.setState(R.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!==R.STOPPED&&(this.videoState.startTransitionTo(R.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(R.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===x.Requested&&Os.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case R.STOPPED:this.videoState.startTransitionTo(R.MANIFEST_READY),this.dash.attachSource(ve(this.params.source.url));return;case R.MANIFEST_READY:this.videoState.startTransitionTo(R.READY),this.prepare();break;case R.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(R.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(R.PLAYING);const d=a?.from;d&&d===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(R.PAUSED)})}return;case R.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(R.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case R.PAUSED:i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(R.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(R.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return 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 xt;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=xe(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!==x.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),Re(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===x.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 Ri 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 xi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ri,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&&(xi.prototype[Symbol.toStringTag]="AbortController",Ri.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?xi: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},ye=(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=ye(c,o):n===b.DocType?t=ye(c,o):n===b.DocTypeReadVersion&&(i=ye(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=ye(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=ye(S,f):p===b.Duration?a=ye(S,f):p===b.SeekPosition&&u===b.Cues?d=ye(S,f):p===b.Tracks?Ke(S,({tag:g,type:A,value:w})=>g===b.ProjectionType?(h=ye(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=ye(u,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:o&&(o.position=ye(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}},Ra=({id:r,bitrate:e})=>({id:r,bitrate:e}),xa=(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 Se=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ae,Ge]=Se.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 Se={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,Se);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,{...Se,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,{...Se,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=ve(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=ve(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=ve(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=ve(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
@@ -34,5 +34,5 @@ precision highp float;
34
34
  #define GLSLIFY 1
35
35
  #endif
36
36
  #define PI 3.14159265358979323846264
37
- varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Ua{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Va(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ma(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Fa,this.gl.VERTEX_SHADER),i=this.createShader(Oa,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,n=e-i,o=t-a,c=e+i,d=t-a,u=e+i,h=t+a,l=e-i,p=t+a;return[n,o,c,d,u,h,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Oi{scene3D;subscription=new s.Subscription;videoState=new z(Q.STOPPED);video;player;params;elementSize$=new s.ValueSubject(void 0);textTracksManager=new Ee;droppedFramesManager=new xt;videoTracks$=new s.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new As;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ba({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=xe(this.video),a=this.constructor.name,n=c=>{e.error$.next({id:a,category:s.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:c})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(c,d)=>this.subscription.add(c.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:n}=this.getProviderSubscriptionInfo();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.videoTracks$.pipe(s.map(u=>u.map(({track:h})=>h)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(s.filter(s.isNonNullable),s.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ye(this.video,t.isLooped,a)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,a)),n(At(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u===le.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();s.assertNonNullable(l,"Manifest not loaded or empty");const p=Array.from(l.audio).sort((g,A)=>A.bitrate-g.bitrate),f=Array.from(l.video).sort((g,A)=>A.bitrate-g.bitrate),S=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const A=Ra(g);A&&this.audioTracks.push({track:A,representation:g})}for(const g of f){const A=_a(g);if(A){h.push({track:A,representation:g});const w=!this.params.tuning.isAudioDisabled&&xa(p,f,g);w&&this.audioRepresentations.set(g.id,w)}}this.videoTracks$.next(h);for(const g of S){const A=Na(g);A&&this.textTracks.push({track:A,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const y=this.selectVideoRepresentation();s.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else u===le.REPRESENTATIOS_READY&&(this.videoState.setState(Q.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:s.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(s.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),h=this.player.state$.getTransition();if(u!==le.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();if(p&&this.params.output.autoVideoTrackLimits$.next(p.to),l){this.player.switchRepresentation(ee.VIDEO,l.id).catch(o);const f=this.audioRepresentations.get(l.id);f&&this.player.switchRepresentation(ee.AUDIO,f.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(s.filterChanged(),s.map(u=>u&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.textTracksManager.connect(this.video,t,e);const c=t.playbackState.stateChangeStarted$.pipe(s.map(({to:u})=>u===exports.PlaybackState.READY),s.filterChanged());this.subscription.add(s.merge(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(s.merge(c,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),n=Be(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,c=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=Ze(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:c,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?u??i:i??u;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===x.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Q.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-o,a.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();return;case Q.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Q.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ua(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){Me(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Q.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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Re(this.video)}}class Ha extends Oi{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class ja extends Oi{constructor(e){super(e),this.liveOffset=new Rt}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(s.combine({interval:s.interval(Yt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()===Q.PLAYING){const n=e.position$.getValue()+(a-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(s.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(s.map(({liveBufferTime:a,liveAvailabilityStartTime:n})=>a&&n?a+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===Q.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(o,a)})}}const be={};var O;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(O||(O={}));const ot=(r,e)=>new s.Observable(t=>{const i=(a,n)=>t.next(n);return r.on(e,i),()=>r.off(e,i)});class Ya{subscription=new s.Subscription;videoState=new z(O.INITIALIZING);video;params;hls;textTracksManager=new Ee;trackLevels=new Map;constructor(e){this.video=_e(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Re(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:s.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(a=>{e||(be.Hls=a.default,be.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(be.Hls,"hls.js not loaded"),this.hls=new be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(O.STOPPED)}subscribe(){s.assertNonNullable(be.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:s.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=xe(this.video),n=(u,h)=>this.subscription.add(u.subscribe(h,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Ye(this.video,e.isLooped,i)),this.subscription.add(Ce(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ve(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(ot(this.hls,be.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:s.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(O.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(O.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===O.READY&&this.videoState.setState(O.READY),this.videoState.getState()===O.PLAYING&&this.playIfAllowed()},i)),n(ot(this.hls,be.Events.MANIFEST_PARSED).pipe(s.map(({levels:u})=>u.reduce((h,l)=>{const p=l.name||l.height.toString(10),{width:f,height:S}=l,y=ft(l.attrs.QUALITY??"")??s.videoSizeToQuality({width:f,height:S});if(!y)return h;const g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,A={id:p.toString(),quality:y,bitrate:l.bitrate/1e3,size:{width:f,height:S},fps:g};return this.trackLevels.set(p,{track:A,level:l}),h.push(A),h},[]))),t.availableVideoTracks$),n(ot(this.hls,be.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const h=[];for(const l of u.subtitleTracks){const p=l.name,f=l.attrs.URI||"",S=l.lang,y="internal";h.push({id:p,url:f,language:S,type:y})}e.internalTextTracks.startTransitionTo(h)}}),n(ot(this.hls,be.Events.LEVEL_LOADING).pipe(s.map(({url:u})=>re(u))),t.hostname$),this.subscription.add(me(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>Array.from(this.trackLevels.values()).find(({level:h})=>h===u)?.track,c=ot(this.hls,be.Events.LEVEL_SWITCHED).pipe(s.map(({level:u})=>o(this.hls.levels[u])));c.pipe(s.filter(s.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(me(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel])?.id,u=>{if(s.isNullable(u))return;const h=this.trackLevels.get(u)?.level;if(!h)return;const l=this.hls.levels.indexOf(h),p=this.hls.currentLevel,f=this.hls.levels[p];!f||h.bitrate>f.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:c.pipe(s.map(u=>u?.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=s.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!==O.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===x.Requested&&this.seek(a.position),t){case exports.PlaybackState.STOPPED:switch(e){case O.STOPPED:break;case O.READY:case O.PLAYING:case O.PAUSED:this.stop();break;default:s.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case O.STOPPED:this.prepare();break;case O.READY:case O.PLAYING:case O.PAUSED:break;default:s.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case O.PLAYING:break;case O.STOPPED:this.prepare();break;case O.READY:case O.PAUSED:this.playIfAllowed();break;default:s.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case O.PAUSED:break;case O.STOPPED:this.prepare();break;case O.READY:this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case O.PLAYING:this.pause();break;default:s.assertNever(e)}break;default:s.assertNever(t)}};prepare(){this.videoState.startTransitionTo(O.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(O.PLAYING),await Me(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(O.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(O.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const hi="X-Playback-Duration";var pi=async r=>{const e=await ht(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(hi)?parseInt(e.headers.get(hi),10):void 0};const Ga=r=>{let e=null;if(r.QUALITY&&(e=ft(r.QUALITY)),!e&&r.RESOLUTION){const[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=s.videoSizeToQuality({width:t,height:i})}return e??null},Ui=async(r,e=r)=>{const a=(await(await ht(r)).text()).split(`
38
- `),n=[],o=[];for(let c=0;c<a.length;c++){const d=a[c],u=d.match(/^#EXT-X-STREAM-INF:(.+)/),h=d.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!h)){if(u){const l=Object.fromEntries(u[1].split(",").map(w=>w.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,f=Ga(l);let S;l.BANDWIDTH&&(S=parseInt(l.BANDWIDTH,10)/1e3||void 0),!S&&l["AVERAGE-BANDWIDTH"]&&(S=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const y=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let g;if(l.RESOLUTION){const[w,m]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));w&&m&&(g={width:w,height:m})}const A=new URL(a[++c],e).toString();f&&n.push({id:p,quality:f,url:A,bandwidth:S,size:g,fps:y})}if(h){const l=Object.fromEntries(h[1].split(",").map(y=>y.split("=")).map(([y,g])=>[y,g.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),f=l.LANGUAGE,S=l.NAME;p&&f&&o.push({type:"internal",id:f,label:S,language:f,url:p,isAuto:!1})}}}return{qualityManifests:n,textTracks:o}};var Y;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(Y||(Y={}));class qa{subscription=new s.Subscription;videoState=new z(Y.STOPPED);video;params;textTracksManager=new Ee;manifests$=new s.ValueSubject([]);maxSeekBackTime$;liveOffset=new Rt;manifestStartTime$=new s.ValueSubject(void 0);constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url};Ui(ve(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.maxSeekBackTime$=new s.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),n=a?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo("master"),o.find(d=>d.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"HlsLiveProvider",category:s.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:c})},a=xe(this.video),n=(c,d)=>this.subscription.add(c.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ce(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(c=>-c/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&s.isNonNullable(u.to)){const l=u.to;this.params.desiredState.videoTrack.setState(l);const p=this.manifests$.getValue().find(f=>f.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),c&&c.state===x.Requested&&this.seek(c.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{const c=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(s.combine({startTime:this.manifestStartTime$.pipe(s.filter(s.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:c,currentTime:d})=>this.params.output.liveTime$.next(c+d*1e3),i)),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:d,quality:u,size:h,bandwidth:l,fps:p})=>({id:d,quality:u,size:h,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?K.DASH_CMAF_OFFSET_P:K.OFFSET_P,i=ve(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),pi(i).then(a=>{if(!s.isNullable(a))this.maxSeekBackTime$.next(a);else{const n=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(s.isNullable(n)||!isFinite(n))try{ht(i).then(o=>o.text()).then(o=>{const c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o)?.[1];if(c){const d=new URL(c,i).toString();pi(d).then(u=>{s.isNullable(u)||this.maxSeekBackTime$.next(u)})}})}catch{}}})}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),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}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED){t!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(n||o){const u=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(u),this.prepare(),d.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!==exports.PlaybackState.PAUSED&&d.state===x.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case Y.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):a?.to===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(q||(q={}));class za{subscription=new s.Subscription;videoState=new z(q.STOPPED);video;params;textTracksManager=new Ee;manifests$=new s.ValueSubject([]);constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),Ui(this.params.source.url).then(({qualityManifests:i,textTracks:a})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(a)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),n=a?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo("master"),o.find(d=>d.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"HlsProvider",category:s.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:c})},a=xe(this.video),n=(c,d)=>this.subscription.add(c.subscribe(d));if(n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Ye(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&s.isNonNullable(u.to)){const l=u.to;this.params.desiredState.videoTrack.setState(l);const p=this.manifests$.getValue().find(f=>f.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===q.CHANGING_MANIFEST&&this.videoState.setState(d.to),c.state===x.Requested&&this.seek(c.position)},i))),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:d,quality:u,size:h,bandwidth:l,fps:p})=>({id:d,quality:u,size:h,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:c}=this.video;this.subscription.add(s.merge(s.fromEvent(c,"addtrack"),s.fromEvent(c,"removetrack"),s.fromEvent(c,"change"),s.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<c.length;d++)c[d].mode="hidden"},i))}const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){const e=this.selectManifest();s.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(q.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(n||o){const u=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(u);const{currentTime:h}=this.video;this.prepare(),d.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:h*1e3,forcePrecise:!0});return}switch(a?.to!==exports.PlaybackState.PAUSED&&d.state===x.Requested&&this.seek(d.position),t){case q.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case q.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var W;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(W||(W={}));class Qa{subscription=new s.Subscription;videoState=new z(W.STOPPED);video;trackUrls={};params;textTracksManager=new Ee;constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"MpegProvider",category:s.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:c})},a=xe(this.video),n=(c,d)=>this.subscription.add(c.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Ye(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY);const c=this.params.desiredState.videoTrack.getTransition();c&&s.isNonNullable(c.to)&&(this.params.desiredState.videoTrack.setState(c.to),this.params.output.currentVideoTrack$.next(this.trackUrls[c.to].track)),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Re(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();s.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];s.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Je(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(re(t))}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(W.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.autoVideoTrackLimits.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(n&&e!==W.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),c.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:d*1e3,forcePrecise:!0}),o.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[o.to]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==exports.PlaybackState.PAUSED&&c.state===x.Requested&&this.seek(c.position),e){case W.READY:t===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}};handleQualityLimitTransition(e){let t;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const i=Object.values(this.trackUrls).find(o=>s.isLowerOrEqual(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState(),n=this.trackUrls[a??"0"]?.track;i&&n&&s.isHigherOrEqual(n.quality,i.quality)&&(t=i)}else if(!e){const i=Object.values(this.trackUrls).map(a=>a.track);t=Ze(i,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const fi=["stun:videostun.mycdn.me:80"],Wa=1e3,Ja=3,Ot=()=>null;class Xa{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ot;externalStopCallback=Ot;externalErrorCallback=Ot;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:fi}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:s.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Wa)}normalizeOptions(e={}){const t={stunServerList:fi,maxRetryNumber:Ja,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var G;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(G||(G={}));class Ka{subscription;params;log;video;videoState=new z(G.STOPPED);liveStreamClient;maxSeekBackTime$=new s.ValueSubject(0);constructor(e){this.subscription=new s.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=_e(e.container),this.liveStreamClient=new Xa(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Re(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:s.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:c})=>{this.log({message:`[videoState change] ${c}: ${JSON.stringify(o)}`})});const a=xe(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ce(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case G.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case G.READY:break;case G.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case G.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(o.to)}},i)).add(s.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:s.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(G.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:s.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(G.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}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case G.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}}class mi{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const Hi=s.getCurrentBrowser().device===s.CurrentClientDevice.Android,_t=document.createElement("video"),Za='video/mp4; codecs="avc1.42000a,mp4a.40.2"',er='video/mp4; codecs="hev1.1.6.L93.B0"',ji='video/webm; codecs="vp09.00.10.08"',Yi='video/webm; codecs="av01.0.00M.08"',tr='audio/mp4; codecs="mp4a.40.2"',ir='audio/webm; codecs="opus"',fe={mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(_t.canPlayType?.("application/x-mpegurl")||_t.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ce={mp4:!!_t.canPlayType?.("video/mp4"),webm:!!_t.canPlayType?.("video/webm"),cmaf:!0},Te={h264:!!window.MediaSource?.isTypeSupported?.(Za),h265:!!window.MediaSource?.isTypeSupported?.(er),vp9:!!window.MediaSource?.isTypeSupported?.(ji),av1:!!window.MediaSource?.isTypeSupported?.(Yi),aac:!!window.MediaSource?.isTypeSupported?.(tr),opus:!!window.MediaSource?.isTypeSupported?.(ir)},ze=(Te.h264||Te.h265)&&Te.aac;var Ie;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Ie||(Ie={}));var De;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(De||(De={}));let Ue;const sr=async()=>{if(!window.navigator.mediaCapabilities)return;const r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Yi}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:ji}})]);Ue={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{sr()}catch(r){console.error(r)}const pt=fe.hls&&ce.mp4,ar=()=>Object.keys(Te).filter(r=>Te[r]),rr=(r,e=!1)=>r.filter(t=>{switch(t){case exports.VideoFormat.DASH:return fe.mse&&ce.mp4&&ze;case exports.VideoFormat.DASH_SEP:return fe.mse&&ce.mp4&&ze;case exports.VideoFormat.DASH_WEBM:return fe.mse&&ce.webm&&Te.vp9&&Te.opus;case exports.VideoFormat.DASH_WEBM_AV1:return fe.mse&&ce.webm&&Te.av1&&Te.opus;case exports.VideoFormat.DASH_LIVE:return fe.mse&&ce.mp4&&ze;case exports.VideoFormat.DASH_LIVE_CMAF:return fe.mse&&ce.mp4&&ze&&ce.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return fe.mse&&ce.mp4&&ze;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return pt||e&&fe.mse&&ce.mp4&&ze;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return pt;case exports.VideoFormat.MPEG:return ce.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return fe.webrtc&&fe.ws&&Te.h264&&(ce.mp4||ce.webm);default:return s.assertNever(t)}}),ct=r=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(r){case Ie.VP9:return[e,t];case Ie.AV1:return[t,e];case Ie.NONE:return[];case Ie.SMOOTH:return Ue?Ue[t].smooth?[t,e]:Ue[e].smooth?[e,t]:[t,e]:[e,t];case Ie.POWER_EFFICIENT:return Ue?Ue[t].powerEfficient?[t,e]:Ue[e].powerEfficient?[e,t]:[t,e]:[e,t];default:s.assertNever(r)}return[e,t]},nr=({webmCodec:r,androidPreferredFormat:e})=>{if(Hi)switch(e){case De.MPEG:return[exports.VideoFormat.MPEG,...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case De.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case De.DASH:return[...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return pt?[...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},or=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],a=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...a],o=[...a,...i];let c;if(Hi)switch(r){case De.DASH:{c=n;break}case De.HLS:case De.MPEG:{c=o;break}}else pt?c=o:c=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...c]:[...c,exports.VideoFormat.WEB_RTC_LIVE]},Si=r=>r?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var cr=r=>new s.Observable(e=>{const t=new s.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(s.map(({from:u,to:h})=>`${u}-${h}`)),a=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$.pipe(s.map(({type:u})=>u!==void 0)),o=new s.Subject;let c=0,d="unknown";return t.add(i.subscribe(u=>{c&&window.clearTimeout(c),d=u,c=window.setTimeout(()=>o.next(u),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(c),d="unknown",c=0})),t.add(n.subscribe(u=>{c&&(window.clearTimeout(c),c=0,u&&(c=window.setTimeout(()=>o.next(d),r.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const ur={cacheDuration:12e4},dr={chunkDuration:5e3,maxParallelRequests:5};class lr{current$=new s.ValueSubject({type:void 0});providerError$=new s.Subject;noAvailableProvidersError$=new s.Subject;providerOutput={position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),volume$:new s.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new s.ValueSubject(void 0),availableVideoTracks$:new s.ValueSubject([]),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new s.ValueSubject(!1),autoVideoTrackLimits$:new s.ValueSubject(void 0),currentBuffer$:new s.ValueSubject(void 0),isBuffering$:new s.ValueSubject(!0),error$:new s.Subject,warning$:new s.Subject,willSeekEvent$:new s.Subject,seekedEvent$:new s.Subject,loopedEvent$:new s.Subject,endedEvent$:new s.Subject,firstBytesEvent$:new s.Subject,firstFrameEvent$:new s.Subject,canplay$:new s.Subject,isLive$:new s.ValueSubject(void 0),isLowLatency$:new s.ValueSubject(!1),canChangePlaybackSpeed$:new s.ValueSubject(!0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),inPiP$:new s.ValueSubject(!1),inFullscreen$:new s.ValueSubject(!1),element$:new s.ValueSubject(void 0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1)};subscription=new s.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=rr([...or(this.params.tuning),...nr(this.params.tuning)],this.params.tuning.useHlsJs).filter(c=>s.isNonNullable(e.sources[c])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning;let n=[];i?n=[i]:a.length?n=[...t.filter(c=>!a.includes(c)),...t.filter(c=>a.includes(c))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new mi(n);const o=[...Si(!0),...Si(!1)];this.chromecastFormatsIterator=new mi(o.filter(c=>s.isNonNullable(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(s.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:s.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==x.None;if(this.params.desiredState.seekState.setState({state:x.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ie.SCREEN:return this.createScreenProvider(t);case ie.CHROMECAST:return this.createChromecastProvider(t);default:return s.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new zs({...o,source:c,config:ur})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),this.params.tuning.useDashJs?new ii({...o,source:c,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new Ha({...o,source:c})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),this.params.tuning.useDashJsCMAF?new ii({...o,source:c,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new ja({...o,source:c})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),pt||!this.params.tuning.useHlsJs?new za({...o,source:c}):new Ya({...o,source:c})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new qa({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Qa({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Hs({...o,source:c,config:{...dr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Ka({container:i,source:c,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return s.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,c=this.params.dependencies.chromecastInitializer.connection$.getValue();return s.assertNonNullable(c),new us({connection:c,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ie.CHROMECAST:ie.SCREEN}chooseFormat(e){switch(e){case ie.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ie.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return s.assertNever(e)}}skipFormat(e){switch(e){case ie.SCREEN:return this.screenFormatsIterator.next();case ie.CHROMECAST:return this.chromecastFormatsIterator.next();default:return s.assertNever(e)}}handleNoFormatsError(e){switch(e){case ie.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ie.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return s.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new s.Subscription;let t=!1,i=0;return e.add(s.merge(this.providerOutput.error$,cr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(s.map(a=>({id:`ProviderHangup:${a}`,category:s.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(s.filter(({to:n})=>n===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===ie.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ie.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===s.ErrorCategory.NETWORK,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit;c&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n??ie.SCREEN)}})),e}}const Gt=(r,e,t)=>t*e+(1-t)*r,Gi=(r,e)=>r.reduce((t,i)=>t+i,0)/e,hr=(r,e,t,i)=>{let a=0,n=t;const o=Gi(r,e),c=e<i?e:i;for(let d=0;d<c;d++)r[n]>o?a++:a--,n=(r.length+n-1)%r.length;return Math.abs(a)===c};class qi{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new s.ValueSubject(e.initial),this.debounced$=new s.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ge(`raw_${t}`),this.smoothedSeries$=new ge(`smoothed_${t}`),this.reportedSeries$=new ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let c=0;c<this.pastMeasures.length;c++)this.pastMeasures[c]!==void 0&&(t+=(this.pastMeasures[c]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(s.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class pr extends qi{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Gt(this.slow,e,this.params.emaAlphaSlow),this.fast=Gt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class fr extends qi{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Gi(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Gt(this.emaSmoothed,e,this.params.emaAlpha);const i=hr(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class bi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new pr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new fr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const mr=5e3,gi="one_video_throughput",yi="one_video_rtt",dt=window.navigator.connection,Ti=()=>{const r=dt?.downlink;if(s.isNonNullable(r)&&r!==10)return r*1e3},vi=()=>{const r=dt?.rtt;if(s.isNonNullable(r)&&r!==3e3)return r},Ei=(r,e,t)=>{const i=t*8,a=i/r;return i/(a+e)};class lt{throughput;rtt;subscription=new s.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=lt.load(gi)||(e.useBrowserEstimation?Ti():void 0)||mr,i=lt.load(yi)??(e.useBrowserEstimation?vi():void 0)??0;if(this.throughput$=new s.ValueSubject(t),this.rtt$=new s.ValueSubject(i),this.rttAdjustedThroughput$=new s.ValueSubject(Ei(t,i,e.rttPenaltyRequestSize)),this.throughput=bi.getSmoothedValue(t,-1,e),this.rtt=bi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const a=()=>{const o=Ti();o&&this.throughput.next(o);const c=vi();s.isNonNullable(c)&&this.rtt.next(c)};dt&&"onchange"in dt&&this.subscription.add(s.fromEvent(dt,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{s.safeStorage.set(gi,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{s.safeStorage.set(yi,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(s.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(s.map(({throughput:a,rtt:n})=>Ei(a,n,e.rttPenaltyRequestSize)),s.filter(a=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=s.now();const a=new s.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(s.fromEvent(e,"progress").pipe(s.once()).subscribe(n=>{t=n.loaded,i=s.now()}));break;case 1:case 0:a.add(s.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=s.now()}));break}a.add(s.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,c=s.now(),d=o-t,u=c-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=s.now();let n=0,o=s.now();const c=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:h})=>{u?(this.addRawSpeed(i,s.now()-a,1),this.concurrentDownloads.delete(e)):h&&(i+=h.byteLength,n+=h.byteLength,n>=this.tuningConfig.streamMinSampleSize&&s.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,s.now()-o,this.concurrentDownloads.size),n=0,o=s.now()),await t?.read().then(d,c))};this.concurrentDownloads.add(e),t?.read().then(d,c)}addRawSpeed(e,t,i=1){if(lt.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){const t=s.safeStorage.get(e);if(s.isNonNullable(t))return parseInt(t,10)??void 0}}const ki={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:s.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Ie.VP9,androidPreferredFormat:De.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Sr=r=>({...s.fillWithDefault(r,ki),configName:[...r.configName??[],...ki.configName]});var $i=({seekState:r,position$:e})=>s.merge(r.stateChangeEnded$.pipe(s.map(({to:t})=>t.state===x.None?void 0:(t.position??NaN)/1e3),s.filter(s.isNonNullable)),e.pipe(s.filter(()=>r.getState().state===x.None))),br=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return s.assertNonNullable(e,`Wrong container or containerId {${r.container}}`),e};class gr{subscription=new s.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new s.Logger;abrLogger=this.logger.createComponentLog("ABR");explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new z(exports.PlaybackState.STOPPED),seekState:new z({state:x.None}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),playbackRate:new z(1),externalTextTracks:new z([]),internalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({}),cameraOrientation:new z({x:0,y:0})};info={playbackState$:new s.ValueSubject(exports.PlaybackState.STOPPED),position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),muted$:new s.ValueSubject(!1),volume$:new s.ValueSubject(1),availableQualities$:new s.ValueSubject([]),availableQualitiesFps$:new s.ValueSubject({}),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),currentQuality$:new s.ValueSubject(void 0),isAutoQualityEnabled$:new s.ValueSubject(!0),autoQualityLimitingAvailable$:new s.ValueSubject(!1),autoQualityLimits$:new s.ValueSubject({}),currentPlaybackRate$:new s.ValueSubject(1),currentBuffer$:new s.ValueSubject({start:0,end:0}),isBuffering$:new s.ValueSubject(!0),isStalled$:new s.ValueSubject(!1),isEnded$:new s.ValueSubject(!1),isLooped$:new s.ValueSubject(!1),isLive$:new s.ValueSubject(void 0),canChangePlaybackSpeed$:new s.ValueSubject(void 0),atLiveEdge$:new s.ValueSubject(void 0),atLiveDurationEdge$:new s.ValueSubject(void 0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),currentFormat$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),throughputEstimation$:new s.ValueSubject(void 0),rttEstimation$:new s.ValueSubject(void 0),videoBitrate$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),surface$:new s.ValueSubject(exports.Surface.NONE),chromecastState$:new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new s.ValueSubject(void 0),intrinsicVideoSize$:new s.ValueSubject(void 0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1)};events={inited$:new s.Subject,ready$:new s.Subject,started$:new s.Subject,playing$:new s.Subject,paused$:new s.Subject,stopped$:new s.Subject,willStart$:new s.Subject,willResume$:new s.Subject,willPause$:new s.Subject,willStop$:new s.Subject,willDestruct$:new s.Subject,watchCoverageRecord$:new s.Subject,watchCoverageLive$:new s.Subject,managedError$:new s.Subject,fatalError$:new s.Subject,ended$:new s.Subject,looped$:new s.Subject,seeked$:new s.Subject,willSeek$:new s.Subject,firstBytes$:new s.Subject,firstFrame$:new s.Subject,canplay$:new s.Subject,log$:new s.Subject};experimental={element$:new s.ValueSubject(void 0),tuningConfigName$:new s.ValueSubject([]),enableDebugTelemetry$:new s.ValueSubject(!1),dumpTelemetry:Es};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Sr(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ss({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new lt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(c){const d=o.map(l=>JSON.stringify(l,(p,f)=>{const S=typeof f;return["number","string","boolean"].includes(S)?f:f===null?null:`<${S}>`})),u=`Player.${String(i)}`,h=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:s.ErrorCategory.WTF,message:h,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.domContainer=br(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new lr({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?s.fromEvent(document,"visibilitychange").pipe(s.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=i&&!a&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:x.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){s.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){s.assertNonNullable(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&this.providerContainer?.providerOutput.availableTextTracks$.getValue().length===0?this.providerContainer?.providerOutput.availableTextTracks$.pipe(s.filter(t=>t.length>0),s.once()).subscribe(t=>{t.find(i=>i.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find(t=>t.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const a=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+n.x,y:a.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){s.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(s.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===x.None?void 0:t.position;return s.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(s.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(s.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(s.filter(({from:e})=>e===exports.PlaybackState.STOPPED),s.once()).subscribe(()=>{this.initedAt=s.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===x.Requested?this.desiredState.seekState.setState({...o,state:x.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:s.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===x.Applying&&(this.desiredState.seekState.setState({state:x.None}),this.events.seeked$.next())})).add(e.current$.pipe(s.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(s.map(o=>o.destination),s.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(s.map(o=>o.map(({quality:c})=>c).sort((c,d)=>s.isInvariantQuality(c)?1:s.isInvariantQuality(d)?-1:s.isHigher(d,c)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const c={};for(const d of o)d.fps&&(c[d.quality]=d.fps);this.info.availableQualitiesFps$.next(c)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o?.quality),this.info.videoBitrate$.next(o?.bitrate)})).add(e.providerOutput.hostname$.pipe(s.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(s.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(s.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o??{})})).add(e.providerOutput.currentBuffer$.pipe(s.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(s.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:$i({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(s.map(({isLive:o,position:c,isLowLatency:d})=>{const u=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(c)<u/1e3}),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(s.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(s.map(({isLive:o,position:c,duration:d})=>o&&Math.abs(d)-Math.abs(c)<this.tuning.live.activeLiveDelay),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(s.map(o=>o.muted),s.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(s.map(o=>o.volume),s.filterChanged()).subscribe(this.info.volume$)).add($i({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(s.merge(e.providerOutput.endedEvent$.pipe(s.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(s.mapTo(!1))).pipe(s.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(s.map(o=>({id:o?`No${o}`:"NoProviders",category:s.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(s.once(),s.map(o=>o??s.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(s.once(),s.map(()=>s.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(s.once(),s.map(()=>s.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new s.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new s.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(s.filter(({to:o})=>o===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>i.next(!1)));let a=0;const n=s.merge(e.providerOutput.isBuffering$,t,i).pipe(s.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),c=t.getValue()||i.getValue();return o&&!c}),s.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(s.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:c?.videoWidth,height:c?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(s.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),c=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let h;u===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:d?o?h=exports.Surface.PIP:c?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE:h=exports.Surface.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(s.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new s.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(s.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(s.filter(i=>i.length>0),s.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Ze(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(s.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(s.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const e=this.providerContainer?.providerOutput;s.assertNonNullable(this.providerContainer),s.assertNonNullable(e),vs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ts(t)),this.providerContainer.current$.subscribe(({type:t})=>Tt("provider",t)),e.duration$.subscribe(t=>Tt("duration",t)),e.availableVideoTracks$.pipe(s.filter(t=>!!t.length),s.once()).subscribe(t=>Tt("tracks",t)),this.events.fatalError$.subscribe(new ge("fatalError")),this.events.managedError$.subscribe(new ge("managedError")),e.position$.subscribe(new ge("position")),e.currentVideoTrack$.pipe(s.map(t=>t?.quality)).subscribe(new ge("quality")),this.info.currentBuffer$.subscribe(new ge("buffer")),e.isBuffering$.subscribe(new ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Tt("codecs",ar())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:s.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(s.merge(s.fromEvent(document,"visibilitychange"),s.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const yr=`@vkontakte/videoplayer-core@${Ai}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return s.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return s.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return s.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return s.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return s.VideoQuality}});exports.Player=gr;exports.SDK_VERSION=yr;exports.VERSION=Ai;
37
+ varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Ua{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Va(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ma(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Fa,this.gl.VERTEX_SHADER),i=this.createShader(Oa,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,n=e-i,o=t-a,c=e+i,d=t-a,u=e+i,h=t+a,l=e-i,p=t+a;return[n,o,c,d,u,h,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Oi{scene3D;subscription=new s.Subscription;videoState=new z(Q.STOPPED);video;player;params;elementSize$=new s.ValueSubject(void 0);textTracksManager=new Ee;droppedFramesManager=new xt;videoTracks$=new s.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new As;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ba({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=xe(this.video),a=this.constructor.name,n=c=>{e.error$.next({id:a,category:s.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:c})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(c,d)=>this.subscription.add(c.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:n}=this.getProviderSubscriptionInfo();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.videoTracks$.pipe(s.map(u=>u.map(({track:h})=>h)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(s.filter(s.isNonNullable),s.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ye(this.video,t.isLooped,a)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,a)),n(At(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u===le.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();s.assertNonNullable(l,"Manifest not loaded or empty");const p=Array.from(l.audio).sort((g,A)=>A.bitrate-g.bitrate),f=Array.from(l.video).sort((g,A)=>A.bitrate-g.bitrate),S=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const A=Ra(g);A&&this.audioTracks.push({track:A,representation:g})}for(const g of f){const A=_a(g);if(A){h.push({track:A,representation:g});const w=!this.params.tuning.isAudioDisabled&&xa(p,f,g);w&&this.audioRepresentations.set(g.id,w)}}this.videoTracks$.next(h);for(const g of S){const A=Na(g);A&&this.textTracks.push({track:A,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const y=this.selectVideoRepresentation();s.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else u===le.REPRESENTATIOS_READY&&(this.videoState.setState(Q.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:s.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(s.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),h=this.player.state$.getTransition();if(u!==le.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();if(p&&this.params.output.autoVideoTrackLimits$.next(p.to),l){this.player.switchRepresentation(ee.VIDEO,l.id).catch(o);const f=this.audioRepresentations.get(l.id);f&&this.player.switchRepresentation(ee.AUDIO,f.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(s.filterChanged(),s.map(u=>u&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.textTracksManager.connect(this.video,t,e);const c=t.playbackState.stateChangeStarted$.pipe(s.map(({to:u})=>u===exports.PlaybackState.READY),s.filterChanged());this.subscription.add(s.merge(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(s.merge(c,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),n=Be(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,c=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=Ze(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:c,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?u??i:i??u;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===x.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Q.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-o,a.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();return;case Q.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Q.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ua(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){Me(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Q.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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Re(this.video)}}class Ha extends Oi{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class ja extends Oi{constructor(e){super(e),this.liveOffset=new Rt}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(s.combine({interval:s.interval(Yt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()===Q.PLAYING){const n=e.position$.getValue()+(a-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(s.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(s.map(({liveBufferTime:a,liveAvailabilityStartTime:n})=>a&&n?a+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===Q.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(o,a)})}}const be={};var O;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(O||(O={}));const ot=(r,e)=>new s.Observable(t=>{const i=(a,n)=>t.next(n);return r.on(e,i),()=>r.off(e,i)});class Ya{subscription=new s.Subscription;videoState=new z(O.INITIALIZING);video;params;hls;textTracksManager=new Ee;trackLevels=new Map;constructor(e){this.video=_e(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Re(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:s.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(a=>{e||(be.Hls=a.default,be.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(be.Hls,"hls.js not loaded"),this.hls=new be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(O.STOPPED)}subscribe(){s.assertNonNullable(be.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:s.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=xe(this.video),n=(u,h)=>this.subscription.add(u.subscribe(h,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Ye(this.video,e.isLooped,i)),this.subscription.add(Ce(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ve(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(ot(this.hls,be.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:s.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(O.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(O.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===O.READY&&this.videoState.setState(O.READY),this.videoState.getState()===O.PLAYING&&this.playIfAllowed()},i)),n(ot(this.hls,be.Events.MANIFEST_PARSED).pipe(s.map(({levels:u})=>u.reduce((h,l)=>{const p=l.name||l.height.toString(10),{width:f,height:S}=l,y=ft(l.attrs.QUALITY??"")??s.videoSizeToQuality({width:f,height:S});if(!y)return h;const g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,A={id:p.toString(),quality:y,bitrate:l.bitrate/1e3,size:{width:f,height:S},fps:g};return this.trackLevels.set(p,{track:A,level:l}),h.push(A),h},[]))),t.availableVideoTracks$),n(ot(this.hls,be.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const h=[];for(const l of u.subtitleTracks){const p=l.name,f=l.attrs.URI||"",S=l.lang,y="internal";h.push({id:p,url:f,language:S,type:y})}e.internalTextTracks.startTransitionTo(h)}}),n(ot(this.hls,be.Events.LEVEL_LOADING).pipe(s.map(({url:u})=>ne(u))),t.hostname$),this.subscription.add(me(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>Array.from(this.trackLevels.values()).find(({level:h})=>h===u)?.track,c=ot(this.hls,be.Events.LEVEL_SWITCHED).pipe(s.map(({level:u})=>o(this.hls.levels[u])));c.pipe(s.filter(s.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(me(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel])?.id,u=>{if(s.isNullable(u))return;const h=this.trackLevels.get(u)?.level;if(!h)return;const l=this.hls.levels.indexOf(h),p=this.hls.currentLevel,f=this.hls.levels[p];!f||h.bitrate>f.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:c.pipe(s.map(u=>u?.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=s.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!==O.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===x.Requested&&this.seek(a.position),t){case exports.PlaybackState.STOPPED:switch(e){case O.STOPPED:break;case O.READY:case O.PLAYING:case O.PAUSED:this.stop();break;default:s.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case O.STOPPED:this.prepare();break;case O.READY:case O.PLAYING:case O.PAUSED:break;default:s.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case O.PLAYING:break;case O.STOPPED:this.prepare();break;case O.READY:case O.PAUSED:this.playIfAllowed();break;default:s.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case O.PAUSED:break;case O.STOPPED:this.prepare();break;case O.READY:this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case O.PLAYING:this.pause();break;default:s.assertNever(e)}break;default:s.assertNever(t)}};prepare(){this.videoState.startTransitionTo(O.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(O.PLAYING),await Me(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(O.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(O.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const hi="X-Playback-Duration";var pi=async r=>{const e=await ht(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(hi)?parseInt(e.headers.get(hi),10):void 0};const Ga=r=>{let e=null;if(r.QUALITY&&(e=ft(r.QUALITY)),!e&&r.RESOLUTION){const[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=s.videoSizeToQuality({width:t,height:i})}return e??null},Ui=async(r,e=r)=>{const a=(await(await ht(r)).text()).split(`
38
+ `),n=[],o=[];for(let c=0;c<a.length;c++){const d=a[c],u=d.match(/^#EXT-X-STREAM-INF:(.+)/),h=d.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!h)){if(u){const l=Object.fromEntries(u[1].split(",").map(w=>w.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,f=Ga(l);let S;l.BANDWIDTH&&(S=parseInt(l.BANDWIDTH,10)/1e3||void 0),!S&&l["AVERAGE-BANDWIDTH"]&&(S=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const y=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let g;if(l.RESOLUTION){const[w,m]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));w&&m&&(g={width:w,height:m})}const A=new URL(a[++c],e).toString();f&&n.push({id:p,quality:f,url:A,bandwidth:S,size:g,fps:y})}if(h){const l=Object.fromEntries(h[1].split(",").map(y=>y.split("=")).map(([y,g])=>[y,g.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),f=l.LANGUAGE,S=l.NAME;p&&f&&o.push({type:"internal",id:f,label:S,language:f,url:p,isAuto:!1})}}}return{qualityManifests:n,textTracks:o}};var Y;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(Y||(Y={}));class qa{subscription=new s.Subscription;videoState=new z(Y.STOPPED);video;params;textTracksManager=new Ee;manifests$=new s.ValueSubject([]);maxSeekBackTime$;liveOffset=new Rt;manifestStartTime$=new s.ValueSubject(void 0);constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url};Ui(ve(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),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.maxSeekBackTime$=new s.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),n=a?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo("master"),o.find(d=>d.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"HlsLiveProvider",category:s.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:c})},a=xe(this.video),n=(c,d)=>this.subscription.add(c.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ce(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(c=>-c/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&s.isNonNullable(u.to)){const l=u.to;this.params.desiredState.videoTrack.setState(l);const p=this.manifests$.getValue().find(f=>f.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ne(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),c&&c.state===x.Requested&&this.seek(c.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{const c=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(s.combine({startTime:this.manifestStartTime$.pipe(s.filter(s.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:c,currentTime:d})=>this.params.output.liveTime$.next(c+d*1e3),i)),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:d,quality:u,size:h,bandwidth:l,fps:p})=>({id:d,quality:u,size:h,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?K.DASH_CMAF_OFFSET_P:K.OFFSET_P,i=ve(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),pi(i).then(a=>{if(!s.isNullable(a))this.maxSeekBackTime$.next(a);else{const n=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(s.isNullable(n)||!isFinite(n))try{ht(i).then(o=>o.text()).then(o=>{const c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o)?.[1];if(c){const d=new URL(c,i).toString();pi(d).then(u=>{s.isNullable(u)||this.maxSeekBackTime$.next(u)})}})}catch{}}})}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),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}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED){t!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(n||o){const u=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(u),this.prepare(),d.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!==exports.PlaybackState.PAUSED&&d.state===x.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case Y.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):a?.to===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var q;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(q||(q={}));class za{subscription=new s.Subscription;videoState=new z(q.STOPPED);video;params;textTracksManager=new Ee;manifests$=new s.ValueSubject([]);constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),Ui(this.params.source.url).then(({qualityManifests:i,textTracks:a})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(a)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),n=a?.to??t.getState()??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo("master"),o.find(d=>d.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"HlsProvider",category:s.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:c})},a=xe(this.video),n=(c,d)=>this.subscription.add(c.subscribe(d));if(n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Ye(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&s.isNonNullable(u.to)){const l=u.to;this.params.desiredState.videoTrack.setState(l);const p=this.manifests$.getValue().find(f=>f.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ne(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===q.CHANGING_MANIFEST&&this.videoState.setState(d.to),c.state===x.Requested&&this.seek(c.position)},i))),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:d,quality:u,size:h,bandwidth:l,fps:p})=>({id:d,quality:u,size:h,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:c}=this.video;this.subscription.add(s.merge(s.fromEvent(c,"addtrack"),s.fromEvent(c,"removetrack"),s.fromEvent(c,"change"),s.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<c.length;d++)c[d].mode="hidden"},i))}const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){const e=this.selectManifest();s.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(q.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(n||o){const u=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(u);const{currentTime:h}=this.video;this.prepare(),d.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:h*1e3,forcePrecise:!0});return}switch(a?.to!==exports.PlaybackState.PAUSED&&d.state===x.Requested&&this.seek(d.position),t){case q.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case q.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var W;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(W||(W={}));class Qa{subscription=new s.Subscription;videoState=new z(W.STOPPED);video;trackUrls={};params;textTracksManager=new Ee;constructor(e){this.params=e,this.video=_e(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"MpegProvider",category:s.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:c})},a=xe(this.video),n=(c,d)=>this.subscription.add(c.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Ye(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY);const c=this.params.desiredState.videoTrack.getTransition();c&&s.isNonNullable(c.to)&&(this.params.desiredState.videoTrack.setState(c.to),this.params.output.currentVideoTrack$.next(this.trackUrls[c.to].track)),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Re(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();s.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];s.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Je(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ne(t))}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(W.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.autoVideoTrackLimits.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(n&&e!==W.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),c.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:d*1e3,forcePrecise:!0}),o.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[o.to]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==exports.PlaybackState.PAUSED&&c.state===x.Requested&&this.seek(c.position),e){case W.READY:t===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}};handleQualityLimitTransition(e){let t;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const i=Object.values(this.trackUrls).find(o=>s.isLowerOrEqual(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState(),n=this.trackUrls[a??"0"]?.track;i&&n&&s.isHigherOrEqual(n.quality,i.quality)&&(t=i)}else if(!e){const i=Object.values(this.trackUrls).map(a=>a.track);t=Ze(i,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const fi=["stun:videostun.mycdn.me:80"],Wa=1e3,Ja=3,Ot=()=>null;class Xa{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ot;externalStopCallback=Ot;externalErrorCallback=Ot;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:fi}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:s.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Wa)}normalizeOptions(e={}){const t={stunServerList:fi,maxRetryNumber:Ja,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var G;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(G||(G={}));class Ka{subscription;params;log;video;videoState=new z(G.STOPPED);liveStreamClient;maxSeekBackTime$=new s.ValueSubject(0);constructor(e){this.subscription=new s.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=_e(e.container),this.liveStreamClient=new Xa(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Re(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:s.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:c})=>{this.log({message:`[videoState change] ${c}: ${JSON.stringify(o)}`})});const a=xe(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ce(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case G.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case G.READY:break;case G.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case G.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(o.to)}},i)).add(s.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:s.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(G.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:s.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video).then(e=>{e||(this.videoState.setState(G.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}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case G.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}}class mi{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const Hi=s.getCurrentBrowser().device===s.CurrentClientDevice.Android,_t=document.createElement("video"),Za='video/mp4; codecs="avc1.42000a,mp4a.40.2"',er='video/mp4; codecs="hev1.1.6.L93.B0"',ji='video/webm; codecs="vp09.00.10.08"',Yi='video/webm; codecs="av01.0.00M.08"',tr='audio/mp4; codecs="mp4a.40.2"',ir='audio/webm; codecs="opus"',fe={mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(_t.canPlayType?.("application/x-mpegurl")||_t.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ue={mp4:!!_t.canPlayType?.("video/mp4"),webm:!!_t.canPlayType?.("video/webm"),cmaf:!0},Te={h264:!!window.MediaSource?.isTypeSupported?.(Za),h265:!!window.MediaSource?.isTypeSupported?.(er),vp9:!!window.MediaSource?.isTypeSupported?.(ji),av1:!!window.MediaSource?.isTypeSupported?.(Yi),aac:!!window.MediaSource?.isTypeSupported?.(tr),opus:!!window.MediaSource?.isTypeSupported?.(ir)},ze=(Te.h264||Te.h265)&&Te.aac;var Ie;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Ie||(Ie={}));var De;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(De||(De={}));let Ue;const sr=async()=>{if(!window.navigator.mediaCapabilities)return;const r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Yi}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:ji}})]);Ue={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{sr()}catch(r){console.error(r)}const pt=fe.hls&&ue.mp4,ar=()=>Object.keys(Te).filter(r=>Te[r]),rr=(r,e=!1)=>r.filter(t=>{switch(t){case exports.VideoFormat.DASH:return fe.mse&&ue.mp4&&ze;case exports.VideoFormat.DASH_SEP:return fe.mse&&ue.mp4&&ze;case exports.VideoFormat.DASH_WEBM:return fe.mse&&ue.webm&&Te.vp9&&Te.opus;case exports.VideoFormat.DASH_WEBM_AV1:return fe.mse&&ue.webm&&Te.av1&&Te.opus;case exports.VideoFormat.DASH_LIVE:return fe.mse&&ue.mp4&&ze;case exports.VideoFormat.DASH_LIVE_CMAF:return fe.mse&&ue.mp4&&ze&&ue.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return fe.mse&&ue.mp4&&ze;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return pt||e&&fe.mse&&ue.mp4&&ze;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return pt;case exports.VideoFormat.MPEG:return ue.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return fe.webrtc&&fe.ws&&Te.h264&&(ue.mp4||ue.webm);default:return s.assertNever(t)}}),ct=r=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(r){case Ie.VP9:return[e,t];case Ie.AV1:return[t,e];case Ie.NONE:return[];case Ie.SMOOTH:return Ue?Ue[t].smooth?[t,e]:Ue[e].smooth?[e,t]:[t,e]:[e,t];case Ie.POWER_EFFICIENT:return Ue?Ue[t].powerEfficient?[t,e]:Ue[e].powerEfficient?[e,t]:[t,e]:[e,t];default:s.assertNever(r)}return[e,t]},nr=({webmCodec:r,androidPreferredFormat:e})=>{if(Hi)switch(e){case De.MPEG:return[exports.VideoFormat.MPEG,...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case De.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case De.DASH:return[...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return pt?[...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...ct(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},or=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],a=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...a],o=[...a,...i];let c;if(Hi)switch(r){case De.DASH:{c=n;break}case De.HLS:case De.MPEG:{c=o;break}}else pt?c=o:c=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...c]:[...c,exports.VideoFormat.WEB_RTC_LIVE]},Si=r=>r?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var cr=r=>new s.Observable(e=>{const t=new s.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(s.map(({from:u,to:h})=>`${u}-${h}`)),a=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$.pipe(s.map(({type:u})=>u!==void 0)),o=new s.Subject;let c=0,d="unknown";return t.add(i.subscribe(u=>{c&&window.clearTimeout(c),d=u,c=window.setTimeout(()=>o.next(u),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(c),d="unknown",c=0})),t.add(n.subscribe(u=>{c&&(window.clearTimeout(c),c=0,u&&(c=window.setTimeout(()=>o.next(d),r.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const ur={cacheDuration:12e4},dr={chunkDuration:5e3,maxParallelRequests:5};class lr{current$=new s.ValueSubject({type:void 0});providerError$=new s.Subject;noAvailableProvidersError$=new s.Subject;providerOutput={position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),volume$:new s.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new s.ValueSubject(void 0),availableVideoTracks$:new s.ValueSubject([]),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new s.ValueSubject(!1),autoVideoTrackLimits$:new s.ValueSubject(void 0),currentBuffer$:new s.ValueSubject(void 0),isBuffering$:new s.ValueSubject(!0),error$:new s.Subject,warning$:new s.Subject,willSeekEvent$:new s.Subject,seekedEvent$:new s.Subject,loopedEvent$:new s.Subject,endedEvent$:new s.Subject,firstBytesEvent$:new s.Subject,firstFrameEvent$:new s.Subject,canplay$:new s.Subject,isLive$:new s.ValueSubject(void 0),isLowLatency$:new s.ValueSubject(!1),canChangePlaybackSpeed$:new s.ValueSubject(!0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),inPiP$:new s.ValueSubject(!1),inFullscreen$:new s.ValueSubject(!1),element$:new s.ValueSubject(void 0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1)};subscription=new s.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=rr([...or(this.params.tuning),...nr(this.params.tuning)],this.params.tuning.useHlsJs).filter(c=>s.isNonNullable(e.sources[c])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning;let n=[];i?n=[i]:a.length?n=[...t.filter(c=>!a.includes(c)),...t.filter(c=>a.includes(c))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new mi(n);const o=[...Si(!0),...Si(!1)];this.chromecastFormatsIterator=new mi(o.filter(c=>s.isNonNullable(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(s.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:s.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==x.None;if(this.params.desiredState.seekState.setState({state:x.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ie.SCREEN:return this.createScreenProvider(t);case ie.CHROMECAST:return this.createChromecastProvider(t);default:return s.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new zs({...o,source:c,config:ur})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),this.params.tuning.useDashJs?new ii({...o,source:c,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new Ha({...o,source:c})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),this.params.tuning.useDashJsCMAF?new ii({...o,source:c,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new ja({...o,source:c})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),pt||!this.params.tuning.useHlsJs?new za({...o,source:c}):new Ya({...o,source:c})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new qa({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Qa({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Hs({...o,source:c,config:{...dr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Ka({container:i,source:c,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return s.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,c=this.params.dependencies.chromecastInitializer.connection$.getValue();return s.assertNonNullable(c),new us({connection:c,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ie.CHROMECAST:ie.SCREEN}chooseFormat(e){switch(e){case ie.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ie.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return s.assertNever(e)}}skipFormat(e){switch(e){case ie.SCREEN:return this.screenFormatsIterator.next();case ie.CHROMECAST:return this.chromecastFormatsIterator.next();default:return s.assertNever(e)}}handleNoFormatsError(e){switch(e){case ie.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ie.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return s.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new s.Subscription;let t=!1,i=0;return e.add(s.merge(this.providerOutput.error$,cr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(s.map(a=>({id:`ProviderHangup:${a}`,category:s.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(s.filter(({to:n})=>n===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===ie.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ie.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===s.ErrorCategory.NETWORK,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit;c&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n??ie.SCREEN)}})),e}}const Gt=(r,e,t)=>t*e+(1-t)*r,Gi=(r,e)=>r.reduce((t,i)=>t+i,0)/e,hr=(r,e,t,i)=>{let a=0,n=t;const o=Gi(r,e),c=e<i?e:i;for(let d=0;d<c;d++)r[n]>o?a++:a--,n=(r.length+n-1)%r.length;return Math.abs(a)===c};class qi{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new s.ValueSubject(e.initial),this.debounced$=new s.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ge(`raw_${t}`),this.smoothedSeries$=new ge(`smoothed_${t}`),this.reportedSeries$=new ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let c=0;c<this.pastMeasures.length;c++)this.pastMeasures[c]!==void 0&&(t+=(this.pastMeasures[c]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(s.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class pr extends qi{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Gt(this.slow,e,this.params.emaAlphaSlow),this.fast=Gt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class fr extends qi{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Gi(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Gt(this.emaSmoothed,e,this.params.emaAlpha);const i=hr(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class bi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new pr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new fr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const mr=5e3,gi="one_video_throughput",yi="one_video_rtt",dt=window.navigator.connection,Ti=()=>{const r=dt?.downlink;if(s.isNonNullable(r)&&r!==10)return r*1e3},vi=()=>{const r=dt?.rtt;if(s.isNonNullable(r)&&r!==3e3)return r},Ei=(r,e,t)=>{const i=t*8,a=i/r;return i/(a+e)};class lt{throughput;rtt;subscription=new s.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=lt.load(gi)||(e.useBrowserEstimation?Ti():void 0)||mr,i=lt.load(yi)??(e.useBrowserEstimation?vi():void 0)??0;if(this.throughput$=new s.ValueSubject(t),this.rtt$=new s.ValueSubject(i),this.rttAdjustedThroughput$=new s.ValueSubject(Ei(t,i,e.rttPenaltyRequestSize)),this.throughput=bi.getSmoothedValue(t,-1,e),this.rtt=bi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const a=()=>{const o=Ti();o&&this.throughput.next(o);const c=vi();s.isNonNullable(c)&&this.rtt.next(c)};dt&&"onchange"in dt&&this.subscription.add(s.fromEvent(dt,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{s.safeStorage.set(gi,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{s.safeStorage.set(yi,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(s.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(s.map(({throughput:a,rtt:n})=>Ei(a,n,e.rttPenaltyRequestSize)),s.filter(a=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=s.now();const a=new s.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(s.fromEvent(e,"progress").pipe(s.once()).subscribe(n=>{t=n.loaded,i=s.now()}));break;case 1:case 0:a.add(s.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=s.now()}));break}a.add(s.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,c=s.now(),d=o-t,u=c-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=s.now();let n=0,o=s.now();const c=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:h})=>{u?(this.addRawSpeed(i,s.now()-a,1),this.concurrentDownloads.delete(e)):h&&(i+=h.byteLength,n+=h.byteLength,n>=this.tuningConfig.streamMinSampleSize&&s.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,s.now()-o,this.concurrentDownloads.size),n=0,o=s.now()),await t?.read().then(d,c))};this.concurrentDownloads.add(e),t?.read().then(d,c)}addRawSpeed(e,t,i=1){if(lt.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){const t=s.safeStorage.get(e);if(s.isNonNullable(t))return parseInt(t,10)??void 0}}const ki={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:s.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Ie.VP9,androidPreferredFormat:De.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Sr=r=>({...s.fillWithDefault(r,ki),configName:[...r.configName??[],...ki.configName]});var $i=({seekState:r,position$:e})=>s.merge(r.stateChangeEnded$.pipe(s.map(({to:t})=>t.state===x.None?void 0:(t.position??NaN)/1e3),s.filter(s.isNonNullable)),e.pipe(s.filter(()=>r.getState().state===x.None))),br=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return s.assertNonNullable(e,`Wrong container or containerId {${r.container}}`),e};class gr{subscription=new s.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new s.Logger;abrLogger=this.logger.createComponentLog("ABR");explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new z(exports.PlaybackState.STOPPED),seekState:new z({state:x.None}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),playbackRate:new z(1),externalTextTracks:new z([]),internalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({}),cameraOrientation:new z({x:0,y:0})};info={playbackState$:new s.ValueSubject(exports.PlaybackState.STOPPED),position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),muted$:new s.ValueSubject(!1),volume$:new s.ValueSubject(1),availableQualities$:new s.ValueSubject([]),availableQualitiesFps$:new s.ValueSubject({}),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),currentQuality$:new s.ValueSubject(void 0),isAutoQualityEnabled$:new s.ValueSubject(!0),autoQualityLimitingAvailable$:new s.ValueSubject(!1),autoQualityLimits$:new s.ValueSubject({}),currentPlaybackRate$:new s.ValueSubject(1),currentBuffer$:new s.ValueSubject({start:0,end:0}),isBuffering$:new s.ValueSubject(!0),isStalled$:new s.ValueSubject(!1),isEnded$:new s.ValueSubject(!1),isLooped$:new s.ValueSubject(!1),isLive$:new s.ValueSubject(void 0),canChangePlaybackSpeed$:new s.ValueSubject(void 0),atLiveEdge$:new s.ValueSubject(void 0),atLiveDurationEdge$:new s.ValueSubject(void 0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),currentFormat$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),throughputEstimation$:new s.ValueSubject(void 0),rttEstimation$:new s.ValueSubject(void 0),videoBitrate$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),surface$:new s.ValueSubject(exports.Surface.NONE),chromecastState$:new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new s.ValueSubject(void 0),intrinsicVideoSize$:new s.ValueSubject(void 0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1)};events={inited$:new s.Subject,ready$:new s.Subject,started$:new s.Subject,playing$:new s.Subject,paused$:new s.Subject,stopped$:new s.Subject,willStart$:new s.Subject,willResume$:new s.Subject,willPause$:new s.Subject,willStop$:new s.Subject,willDestruct$:new s.Subject,watchCoverageRecord$:new s.Subject,watchCoverageLive$:new s.Subject,managedError$:new s.Subject,fatalError$:new s.Subject,ended$:new s.Subject,looped$:new s.Subject,seeked$:new s.Subject,willSeek$:new s.Subject,firstBytes$:new s.Subject,firstFrame$:new s.Subject,canplay$:new s.Subject,log$:new s.Subject};experimental={element$:new s.ValueSubject(void 0),tuningConfigName$:new s.ValueSubject([]),enableDebugTelemetry$:new s.ValueSubject(!1),dumpTelemetry:Es};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Sr(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ss({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new lt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(c){const d=o.map(l=>JSON.stringify(l,(p,f)=>{const S=typeof f;return["number","string","boolean"].includes(S)?f:f===null?null:`<${S}>`})),u=`Player.${String(i)}`,h=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:s.ErrorCategory.WTF,message:h,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.domContainer=br(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new lr({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?s.fromEvent(document,"visibilitychange").pipe(s.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=i&&!a&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:x.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){s.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){s.assertNonNullable(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&this.providerContainer?.providerOutput.availableTextTracks$.getValue().length===0?this.providerContainer?.providerOutput.availableTextTracks$.pipe(s.filter(t=>t.length>0),s.once()).subscribe(t=>{t.find(i=>i.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find(t=>t.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const a=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+n.x,y:a.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){s.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(s.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===x.None?void 0:t.position;return s.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(s.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(s.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(s.filter(({from:e})=>e===exports.PlaybackState.STOPPED),s.once()).subscribe(()=>{this.initedAt=s.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===x.Requested?this.desiredState.seekState.setState({...o,state:x.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:s.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===x.Applying&&(this.desiredState.seekState.setState({state:x.None}),this.events.seeked$.next())})).add(e.current$.pipe(s.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(s.map(o=>o.destination),s.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(s.map(o=>o.map(({quality:c})=>c).sort((c,d)=>s.isInvariantQuality(c)?1:s.isInvariantQuality(d)?-1:s.isHigher(d,c)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const c={};for(const d of o)d.fps&&(c[d.quality]=d.fps);this.info.availableQualitiesFps$.next(c)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o?.quality),this.info.videoBitrate$.next(o?.bitrate)})).add(e.providerOutput.hostname$.pipe(s.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(s.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(s.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o??{})})).add(e.providerOutput.currentBuffer$.pipe(s.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(s.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:$i({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(s.map(({isLive:o,position:c,isLowLatency:d})=>{const u=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(c)<u/1e3}),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(s.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(s.map(({isLive:o,position:c,duration:d})=>o&&Math.abs(d)-Math.abs(c)<this.tuning.live.activeLiveDelay),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(s.map(o=>o.muted),s.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(s.map(o=>o.volume),s.filterChanged()).subscribe(this.info.volume$)).add($i({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(s.merge(e.providerOutput.endedEvent$.pipe(s.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(s.mapTo(!1))).pipe(s.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(s.map(o=>({id:o?`No${o}`:"NoProviders",category:s.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(s.once(),s.map(o=>o??s.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(s.once(),s.map(()=>s.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(s.once(),s.map(()=>s.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new s.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new s.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(s.filter(({to:o})=>o===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>i.next(!1)));let a=0;const n=s.merge(e.providerOutput.isBuffering$,t,i).pipe(s.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),c=t.getValue()||i.getValue();return o&&!c}),s.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(s.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:c?.videoWidth,height:c?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(s.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),c=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let h;u===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:d?o?h=exports.Surface.PIP:c?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE:h=exports.Surface.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(s.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new s.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(s.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(s.filter(i=>i.length>0),s.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Ze(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(s.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(s.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const e=this.providerContainer?.providerOutput;s.assertNonNullable(this.providerContainer),s.assertNonNullable(e),vs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ts(t)),this.providerContainer.current$.subscribe(({type:t})=>Tt("provider",t)),e.duration$.subscribe(t=>Tt("duration",t)),e.availableVideoTracks$.pipe(s.filter(t=>!!t.length),s.once()).subscribe(t=>Tt("tracks",t)),this.events.fatalError$.subscribe(new ge("fatalError")),this.events.managedError$.subscribe(new ge("managedError")),e.position$.subscribe(new ge("position")),e.currentVideoTrack$.pipe(s.map(t=>t?.quality)).subscribe(new ge("quality")),this.info.currentBuffer$.subscribe(new ge("buffer")),e.isBuffering$.subscribe(new ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Tt("codecs",ar())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:s.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(s.merge(s.fromEvent(document,"visibilitychange"),s.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const yr=`@vkontakte/videoplayer-core@${Ai}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return s.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return s.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return s.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return s.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return s.VideoQuality}});exports.Player=gr;exports.SDK_VERSION=yr;exports.VERSION=Ai;