@vkontakte/videoplayer-core 2.0.99 → 2.0.100

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.99
3
- * Mon, 08 Apr 2024 01:38:49 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-99/doc/
2
+ * @vkontakte/videoplayer-core v2.0.100
3
+ * Fri, 12 Apr 2024 14:49:51 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-100/doc/
5
5
  */
6
- "use strict";var qi=Object.create;var Kt=Object.defineProperty;var zi=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var Wi=Object.getPrototypeOf,Ji=Object.prototype.hasOwnProperty;var Xi=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Qi(e))!Ji.call(r,a)&&a!==t&&Kt(r,a,{get:()=>e[a],enumerable:!(i=zi(e,a))||i.enumerable});return r};var Ki=(r,e,t)=>(t=r!=null?qi(Wi(r)):{},Xi(e||!r||!r.__esModule?Kt(t,"default",{value:r,enumerable:!0}):t,r));var s=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const wi="2.0.99";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_SEP",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 Z;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(Z||(Z={}));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 V;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(V||(V={}));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 Zi=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 es{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||Zi("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(ts),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 u=c.getCastDevice(),l=c.getMediaSession()?.media.contentId;(s.isNullable(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:u}))}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 ts=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 J;(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"})(J||(J={}));var fe=(r,e=0,t=J.OFFSET_P)=>{switch(t){case J.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case J.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case J.DASH_CMAF_OFFSET_P:{const i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:s.assertNever(t)}return r};const Zt=(r,e)=>{switch(e){case J.OFFSET_P:return NaN;case J.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case J.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:s.assertNever(e)}};var w=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class q{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 is=r=>{switch(r){case exports.VideoFormat.MPEG: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 D;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(D||(D={}));const ss=5,as=5,rs=500,ei=7e3;class ns{subscription=new s.Subscription;loadMediaTimeoutSubscription=new s.Subscription;videoState=new q(D.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(is(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(rs)).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===V.Applying||Math.abs(c-n)>ss)&&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(),u=o===chrome.cast.media.PlayerState.BUFFERING;switch(c!==u&&this.params.output.isBuffering$.next(u),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<as&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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(D.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(D.PLAYING),w(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:V.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===D.PAUSED||e===D.PLAYING)&&(this.videoState.setState(D.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===D.PLAYING||e===D.PAUSED)&&(this.videoState.setState(D.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===D.READY&&this.videoState.setState(D.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==D.STOPPED&&this.videoState.setState(D.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),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 l=t[e];s.assertNonNullable(l);const d=s.getHighestQuality(Object.keys(l));s.assertNonNullable(d);const h=l[d];s.assertNonNullable(h),i=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=t[e];s.assertNonNullable(l),i=l.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 l=t[e];s.assertNonNullable(l),i=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=t[e];s.assertNonNullable(l),i=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=t[e];s.assertNonNullable(l),i=fe(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:s.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:d}),d}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:u}=this.params.meta;return s.isNonNullable(c)&&(o.metadata.title=c),s.isNonNullable(u)&&(o.metadata.subtitle=u),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===V.Applying||i.state===V.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===V.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!==D.STOPPED&&(this.videoState.startTransitionTo(D.STOPPED),this.stop());return}if(!t){if(a?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&e!==D.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case D.PLAYING:case D.PAUSED:case D.READY:break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case D.PLAYING:break;case D.PAUSED:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.READY:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case D.PLAYING:this.videoState.startTransitionTo(D.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case D.PAUSED:break;case D.READY:this.videoState.startTransitionTo(D.PAUSED),this.videoState.setState(D.PAUSED);break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}default:s.assertNever(i)}}}}const qt=r=>{r.removeAttribute("src"),r.load()},os=r=>{try{r.pause(),r.playbackRate=0,qt(r),r.remove()}catch(e){console.error(e)}};class cs{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 Ft=window.WeakMap?new WeakMap:new cs,Fe=r=>{let e=r.querySelector("video");const t=!!e;return e?qt(e):(e=document.createElement("video"),r.appendChild(e)),Ft.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Oe=r=>{const e=Ft.get(r);Ft.delete(r),e?qt(r):os(r)},ke=(r,e,t,{equal:i=(o,c)=>o===c,changed$:a,onError:n}={})=>{const o=r.getState(),c=e(),u=s.isNullable(a),l=new s.Subscription;return a&&l.add(a.subscribe(d=>{const h=r.getState();i(d,h)&&r.setState(d)},n)),i(c,o)||(t(o),u&&r.setState(o)),l.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),u&&r.setState(d.to)},n)),l},ht=(r,e,t)=>ke(e,()=>r.loop,i=>{s.isNonNullable(i)&&(r.loop=i)},{onError:t}),Ue=(r,e,t,i)=>ke(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}),Ze=(r,e,t,i)=>ke(e,()=>r.playbackRate,a=>{s.isNonNullable(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),ls=r=>["__",r.language,r.label].join("|"),us=(r,e)=>{if(r.id===e)return!0;const[t,i,a]=e.split("|");return r.language===i&&r.label===a};class xe{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(ke(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},u)=>c===o[u].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(ke(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},u)=>c===o[u].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(ke(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(ke(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(xe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id?e.id:ls(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)||!us(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)}}class zt{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 Ai=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ti=r=>{const e=Ai(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},ds=r=>{const e=Ai(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},hs=3;var fs=(r,e,t=hs)=>{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 u=n-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=n+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};const He=r=>{const e=P=>s.fromEvent(r,P).pipe(s.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=s.merge(...t.map(P=>s.fromEvent(r,P))).pipe(s.map(P=>P.type==="ended"?r.readyState<2:r.readyState<3),s.filterChanged()),a=s.merge(s.fromEvent(r,"progress"),s.fromEvent(r,"timeupdate")).pipe(s.map(()=>fs(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}))),u=s.fromEvent(r,"ratechange").pipe(s.map(()=>r.playbackRate)),l=s.fromEvent(r,"error").pipe(s.filter(()=>!!(r.error||r.played.length)),s.map(()=>{const P=r.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:s.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:r.error??void 0}})),d=s.fromEvent(r,"timeupdate").pipe(s.map(()=>r.currentTime)),h=new s.Subject,f=.3;let p;d.subscribe(P=>{r.loop&&s.isNonNullable(p)&&s.isNonNullable(P)&&p>=r.duration-f&&P<=f&&h.next(p),p=P});const m=s.fromEvent(r,"enterpictureinpicture"),T=s.fromEvent(r,"leavepictureinpicture"),b=new s.ValueSubject(ds(r));m.subscribe(()=>b.next(!0)),T.subscribe(()=>b.next(!1));const y=new s.ValueSubject(ti(r));return s.fromEvent(r,"fullscreenchange").pipe(s.map(()=>ti(r))).subscribe(y),{playing$:o,pause$:e("pause").pipe(s.filter(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:s.fromEvent(r,"durationchange").pipe(s.map(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:c,playbackRateState$:u,inPiP$:b,inFullscreen$:y}};var $t=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}};let Qt=!1,we={};const ps=r=>{Qt=r},ms=()=>{we={}},Ss=r=>{r(we)},gt=(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 Be;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(Be||(Be={}));const bs=new ge("best_bitrate"),gs=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class ys{last;history={};recordSelection(e){this.history[e.id]=s.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const vs='Assertion "ABR Tracks is empty array" failed',Pt=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:u,history:l,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{s.assertNotEmptyArray(r,vs);const f=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*i.containerSizeFactor,height:e.height*f*i.containerSizeFactor},m=p&&s.videoSizeToQuality(p),T=i.considerPlaybackRate&&s.isNonNullable(c)?c:1,b=r.filter(k=>!s.isInvariantQuality(k.quality)).sort((k,A)=>s.isHigher(k.quality,A.quality)?-1:1),y=b.at(-1)?.quality,C=b.at(0)?.quality,P=s.isNullable(a)||s.isNonNullable(a.min)&&s.isNonNullable(a.max)&&s.isLower(a.max,a.min)||s.isNonNullable(a.min)&&C&&s.isHigher(a.min,C)||s.isNonNullable(a.max)&&y&&s.isLower(a.max,y),g=T*gs(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},I=b.filter(k=>(m?s.isLower(k.quality,m):!0)?(s.isNonNullable(t)&&isFinite(t)&&s.isNonNullable(k.bitrate)?t-n>=k.bitrate*g:!0)?i.lazyQualitySwitch&&s.isNonNullable(i.minBufferToSwitchUp)&&u&&!s.isInvariantQuality(u.quality)&&(o??0)<i.minBufferToSwitchUp&&s.isHigher(k.quality,u.quality)?(E[k.quality]=Be.Buffer,!1):!!d&&s.isHigherOrEqual(k.quality,d)?(E[k.quality]=Be.DroppedFramesLimit,!1):P||(s.isNullable(a.max)||s.isLowerOrEqual(k.quality,a.max))&&(s.isNullable(a.min)||s.isHigherOrEqual(k.quality,a.min))?!0:(E[k.quality]=Be.FitsQualityLimits,!1):(E[k.quality]=Be.FitsThroughput,!1):(E[k.quality]=Be.FitsContainer,!1))[0];I&&I.bitrate&&bs.next(I.bitrate);const R=I??b[Math.ceil((b.length-1)/2)]??r[0];R.quality!==l?.last?.quality&&h({message:`
6
+ "use strict";var qi=Object.create;var Kt=Object.defineProperty;var zi=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var Wi=Object.getPrototypeOf,Ji=Object.prototype.hasOwnProperty;var Xi=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Qi(e))!Ji.call(r,a)&&a!==t&&Kt(r,a,{get:()=>e[a],enumerable:!(i=zi(e,a))||i.enumerable});return r};var Ki=(r,e,t)=>(t=r!=null?qi(Wi(r)):{},Xi(e||!r||!r.__esModule?Kt(t,"default",{value:r,enumerable:!0}):t,r));var s=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const wi="2.0.100";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_SEP",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 Z;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(Z||(Z={}));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 I;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(I||(I={}));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 Zi=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 es{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||Zi("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(ts),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 u=c.getCastDevice(),l=c.getMediaSession()?.media.contentId;(s.isNullable(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:u}))}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 ts=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 J;(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"})(J||(J={}));var fe=(r,e=0,t=J.OFFSET_P)=>{switch(t){case J.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case J.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case J.DASH_CMAF_OFFSET_P:{const i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:s.assertNever(t)}return r};const Zt=(r,e)=>{switch(e){case J.OFFSET_P:return NaN;case J.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case J.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:s.assertNever(e)}};var w=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class q{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 is=r=>{switch(r){case exports.VideoFormat.MPEG: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 D;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(D||(D={}));const ss=5,as=5,rs=500,ei=7e3;class ns{subscription=new s.Subscription;loadMediaTimeoutSubscription=new s.Subscription;videoState=new q(D.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(is(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(rs)).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===I.Applying||Math.abs(c-n)>ss)&&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(),u=o===chrome.cast.media.PlayerState.BUFFERING;switch(c!==u&&this.params.output.isBuffering$.next(u),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<as&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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(D.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(D.PLAYING),w(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:I.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===D.PAUSED||e===D.PLAYING)&&(this.videoState.setState(D.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===D.PLAYING||e===D.PAUSED)&&(this.videoState.setState(D.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===D.READY&&this.videoState.setState(D.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==D.STOPPED&&this.videoState.setState(D.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),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 l=t[e];s.assertNonNullable(l);const d=s.getHighestQuality(Object.keys(l));s.assertNonNullable(d);const h=l[d];s.assertNonNullable(h),i=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=t[e];s.assertNonNullable(l),i=l.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 l=t[e];s.assertNonNullable(l),i=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=t[e];s.assertNonNullable(l),i=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=t[e];s.assertNonNullable(l),i=fe(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:s.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:d}),d}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:u}=this.params.meta;return s.isNonNullable(c)&&(o.metadata.title=c),s.isNonNullable(u)&&(o.metadata.subtitle=u),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===I.Applying||i.state===I.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===I.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!==D.STOPPED&&(this.videoState.startTransitionTo(D.STOPPED),this.stop());return}if(!t){if(a?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&e!==D.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case D.PLAYING:case D.PAUSED:case D.READY:break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case D.PLAYING:break;case D.PAUSED:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.READY:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case D.PLAYING:this.videoState.startTransitionTo(D.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case D.PAUSED:break;case D.READY:this.videoState.startTransitionTo(D.PAUSED),this.videoState.setState(D.PAUSED);break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}default:s.assertNever(i)}}}}const qt=r=>{r.removeAttribute("src"),r.load()},os=r=>{try{r.pause(),r.playbackRate=0,qt(r),r.remove()}catch(e){console.error(e)}};class cs{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 Ft=window.WeakMap?new WeakMap:new cs,Fe=r=>{let e=r.querySelector("video");const t=!!e;return e?qt(e):(e=document.createElement("video"),r.appendChild(e)),Ft.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Oe=r=>{const e=Ft.get(r);Ft.delete(r),e?qt(r):os(r)},ke=(r,e,t,{equal:i=(o,c)=>o===c,changed$:a,onError:n}={})=>{const o=r.getState(),c=e(),u=s.isNullable(a),l=new s.Subscription;return a&&l.add(a.subscribe(d=>{const h=r.getState();i(d,h)&&r.setState(d)},n)),i(c,o)||(t(o),u&&r.setState(o)),l.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),u&&r.setState(d.to)},n)),l},ht=(r,e,t)=>ke(e,()=>r.loop,i=>{s.isNonNullable(i)&&(r.loop=i)},{onError:t}),Ue=(r,e,t,i)=>ke(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}),Ze=(r,e,t,i)=>ke(e,()=>r.playbackRate,a=>{s.isNonNullable(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),ls=r=>["__",r.language,r.label].join("|"),us=(r,e)=>{if(r.id===e)return!0;const[t,i,a]=e.split("|");return r.language===i&&r.label===a};class xe{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(ke(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},u)=>c===o[u].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(ke(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},u)=>c===o[u].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(ke(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(ke(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(xe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id?e.id:ls(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)||!us(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)}}class zt{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 Ai=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ti=r=>{const e=Ai(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},ds=r=>{const e=Ai(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},hs=3;var fs=(r,e,t=hs)=>{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 u=n-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=n+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};const He=r=>{const e=P=>s.fromEvent(r,P).pipe(s.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=s.merge(...t.map(P=>s.fromEvent(r,P))).pipe(s.map(P=>P.type==="ended"?r.readyState<2:r.readyState<3),s.filterChanged()),a=s.merge(s.fromEvent(r,"progress"),s.fromEvent(r,"timeupdate")).pipe(s.map(()=>fs(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}))),u=s.fromEvent(r,"ratechange").pipe(s.map(()=>r.playbackRate)),l=s.fromEvent(r,"error").pipe(s.filter(()=>!!(r.error||r.played.length)),s.map(()=>{const P=r.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:s.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:r.error??void 0}})),d=s.fromEvent(r,"timeupdate").pipe(s.map(()=>r.currentTime)),h=new s.Subject,f=.3;let p;d.subscribe(P=>{r.loop&&s.isNonNullable(p)&&s.isNonNullable(P)&&p>=r.duration-f&&P<=f&&h.next(p),p=P});const m=s.fromEvent(r,"enterpictureinpicture"),T=s.fromEvent(r,"leavepictureinpicture"),b=new s.ValueSubject(ds(r));m.subscribe(()=>b.next(!0)),T.subscribe(()=>b.next(!1));const g=new s.ValueSubject(ti(r));return s.fromEvent(r,"fullscreenchange").pipe(s.map(()=>ti(r))).subscribe(g),{playing$:o,pause$:e("pause").pipe(s.filter(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:s.fromEvent(r,"durationchange").pipe(s.map(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:c,playbackRateState$:u,inPiP$:b,inFullscreen$:g}};var $t=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}};let Qt=!1,we={};const ps=r=>{Qt=r},ms=()=>{we={}},Ss=r=>{r(we)},gt=(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 Me;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(Me||(Me={}));const bs=new ge("best_bitrate"),gs=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class ys{last;history={};recordSelection(e){this.history[e.id]=s.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const vs='Assertion "ABR Tracks is empty array" failed',Pt=(r,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:u,history:l,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{s.assertNotEmptyArray(r,vs);const f=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*i.containerSizeFactor,height:e.height*f*i.containerSizeFactor},m=p&&s.videoSizeToQuality(p),T=i.considerPlaybackRate&&s.isNonNullable(c)?c:1,b=r.filter(k=>!s.isInvariantQuality(k.quality)).sort((k,A)=>s.isHigher(k.quality,A.quality)?-1:1),g=b.at(-1)?.quality,C=b.at(0)?.quality,P=s.isNullable(a)||s.isNonNullable(a.min)&&s.isNonNullable(a.max)&&s.isLower(a.max,a.min)||s.isNonNullable(a.min)&&C&&s.isHigher(a.min,C)||s.isNonNullable(a.max)&&g&&s.isLower(a.max,g),y=T*gs(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},V=b.filter(k=>(m?s.isLower(k.quality,m):!0)?(s.isNonNullable(t)&&isFinite(t)&&s.isNonNullable(k.bitrate)?t-n>=k.bitrate*y:!0)?i.lazyQualitySwitch&&s.isNonNullable(i.minBufferToSwitchUp)&&u&&!s.isInvariantQuality(u.quality)&&(o??0)<i.minBufferToSwitchUp&&s.isHigher(k.quality,u.quality)?(E[k.quality]=Me.Buffer,!1):!!d&&s.isHigherOrEqual(k.quality,d)?(E[k.quality]=Me.DroppedFramesLimit,!1):P||(s.isNullable(a.max)||s.isLowerOrEqual(k.quality,a.max))&&(s.isNullable(a.min)||s.isHigherOrEqual(k.quality,a.min))?!0:(E[k.quality]=Me.FitsQualityLimits,!1):(E[k.quality]=Me.FitsThroughput,!1):(E[k.quality]=Me.FitsContainer,!1))[0];V&&V.bitrate&&bs.next(V.bitrate);const R=V??b[Math.ceil((b.length-1)/2)]??r[0];R.quality!==l?.last?.quality&&h({message:`
7
7
  [available tracks]
8
8
  ${r.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
9
  `)}
@@ -19,7 +19,7 @@
19
19
  playbackRate: ${c},
20
20
  playbackRateFactor: ${T},
21
21
  forwardBufferHealth: ${o},
22
- bitrateFactor: ${g},
22
+ bitrateFactor: ${y},
23
23
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
24
24
  droppedVideoMaxQualityLimit: ${d},
25
25
  limitsAreInvalid: ${P},
@@ -30,11 +30,11 @@
30
30
  ${Object.entries(E).map(([k,A])=>`${k}: ${A}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${I?.quality}
33
+ [best track] ${V?.quality}
34
34
  [selected track] ${R?.quality}
35
- `});const _=R&&l&&l.history[R.id]&&s.now()-l.history[R.id]<=i.trackCooldown&&(!l.last||R.id!==l.last.id);if(R?.id&&l&&!_&&l.recordSelection(R),_&&l?.last){const k=l.last;return l?.recordSwitch(k),h({message:`
35
+ `});const M=R&&l&&l.history[R.id]&&s.now()-l.history[R.id]<=i.trackCooldown&&(!l.last||R.id!==l.last.id);if(R?.id&&l&&!M&&l.recordSelection(R),M&&l?.last){const k=l.last;return l?.recordSwitch(k),h({message:`
36
36
  [last selected] ${k?.quality}
37
- `}),k}return l?.recordSwitch(R),R};var Te=r=>new URL(r).hostname;const ii=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 je=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!ii(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return ii(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function ee(){return s.now()}function $i(r){return ee()-r}function si(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,u=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let l=o.indexOf("?")>-1?"&":"?";return u&&(o+=l+"lowLat=1",l="&"),c&&(o+=l+"_rnd="+Math.floor(999999999*Math.random())),o}}}function Ts(r,e,t){const i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function vt(r,e,t,i){const a=window.XMLHttpRequest;let n,o,c,u=!1,l=0,d,h,f=!1,p="arraybuffer",m=7e3,T=2e3,b=()=>{if(u)return;s.assertNonNullable(d);const N=$i(d);let z;if(N<T){z=T-N,setTimeout(b,z);return}T*=2,T>m&&(T=m),o&&o.abort(),o=new a,B()};const y=N=>(n=N,A),C=N=>(h=N,A),P=()=>(p="json",A),g=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,h&&h(),t&&t()}},E=N=>(f=N,A),B=()=>{d=ee(),o=new a,o.open("get",r);let N=0,z,X=0;const le=()=>(s.assertNonNullable(d),Math.max(d,Math.max(z||0,X||0)));if(n&&o.addEventListener("progress",$=>{const O=ee();n.updateChunk&&$.loaded>N&&(n.updateChunk(le(),$.loaded-N),N=$.loaded,z=O)}),c&&(o.timeout=c,o.addEventListener("timeout",()=>g())),o.addEventListener("load",()=>{if(u)return;s.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const O=o.response.byteLength-N;O&&n.updateChunk&&n.updateChunk(le(),O)}o.responseType==="json"&&!Object.values(o.response).length?g():(h&&h(),e(o.response))}else g()}),o.addEventListener("error",()=>{g()}),f){const $=()=>{s.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(X=ee(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),A},A={withBitrateReporting:y,withParallel:E,withJSONResponse:P,withRetryCount:N=>(l=N,A),withRetryInterval:(N,z)=>(s.isNonNullable(N)&&(T=N),s.isNonNullable(z)&&(m=z),A),withTimeout:N=>(c=N,A),withFinally:C,send:B,abort:()=>{o&&(o.abort(),o=void 0),u=!0,h&&h()}};return A}const Es=100,ks=2e3,ws=500;let As=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-ws;if(t-e>ks){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 u=n.bytes*o/c;a+=u,n.start=t,n.bytes-=u}}}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>Es&&(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 $s{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=ee(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},c=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=vt(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=ee()}_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=ee();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 yt=1e4,Mt=3,Ps=6e4,Cs=10,Ds=1,Ls=500;class xs{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 As(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=si(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=si(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=()=>{Ts(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 $s(Mt,yt,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,u=null,l=null,d=!1;const h=()=>{const g=n&&(!d||d===this.rep);return g||t("Not running!"),g},f=(g,E,B)=>{u&&u.abort(),u=vt(this.urlResolver.resolve(g,!1),E,B,()=>this._retryCallback()).withTimeout(yt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mt).withFinally(()=>{u=null}).send()},p=(g,E,B)=>{s.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),E,B,()=>this._retryCallback()).withFinally(()=>{c=null}).send()},m=g=>{const E=i.playbackRate;i.playbackRate!==g&&(t(`Playback rate switch: ${E}=>${g}`),i.playbackRate=g)},T=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const B=ee()-1e4;let I=0;for(let _=0;_<this.bufferStates.length;_++){const k=this.bufferStates[_];g=Math.min(g,k.buf),k.ts<B&&I++}this.bufferStates.splice(0,I),t(`update playback rate; minBuffer=${g} drop=${I} jitter=${this.sourceJitter}`);let R=g-Ds;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?m(1.15):R>1?m(1.1):R>.3?m(1.05):m(1)}},y=g=>{let E;const B=()=>E&&E.start?E.start.length:0,I=$=>E.start[$]/1e3,R=$=>E.dur[$]/1e3,_=$=>E.fragIndex+$,k=($,O)=>({chunkIdx:_($),startTS:I($),dur:R($),discontinuity:O}),A=()=>{let $=0;if(E&&E.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=O;this.sourceJitter>1&&(W+=this.sourceJitter-1);let te=E.dur.length-1;for(;te>=0&&(W-=E.dur[te],!(W<=0));--te);$=Math.min(te,E.dur.length-1-Q),$=Math.max($,0)}return k($,!0)},N=$=>{const O=B();if(!(O<=0)){if(s.isNonNullable($)){for(let Q=0;Q<O;Q++)if(I(Q)>$)return k(Q)}return A()}},z=$=>{const O=B(),Q=$?$.chunkIdx+1:0,W=Q-E.fragIndex;if(!(O<=0)){if(!$||W<0||W-O>Cs)return t(`Resync: offset=${W} bChunks=${O} chunk=`+JSON.stringify($)),A();if(!(W>=O))return k(Q-E.fragIndex,!1)}},X=($,O,Q)=>{l&&l.abort(),l=vt(this.urlResolver.resolve($,!0,this.lowLatency),O,Q,()=>this._retryCallback()).withTimeout(yt).withRetryCount(Mt).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,O)=>{X(g,Q=>{if(!h())return;E=Q;const W=!!E.lowLatency;W!==this.lowLatency&&T(W);let te=0;for(let Pe=0;Pe<E.dur.length;++Pe)te+=E.dur[Pe];te>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(N(O))},()=>this._handleNetworkError())},nextChunk:z}},C=()=>{n=!1,c&&c.abort(),u&&u.abort(),l&&l.abort(),s.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:g=>{const{videoElement:E,logger:B}=this.params;let I=y(e.jidxUrl),R,_,k,A,N=0,z,X,le;const $=()=>{z&&(clearTimeout(z),z=void 0);const F=Math.max(Ls,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=N+F,se=ee(),ue=Math.min(1e4,ie-se);N=se;const Ee=()=>{l||h()&&I.seek(()=>{h()&&(N=ee(),O(),$())})};ue>0?z=window.setTimeout(()=>{this.paused?$():Ee()},ue):Ee()},O=()=>{let F;for(;F=I.nextChunk(A);)A=F,Lt(F);const ie=I.nextChunk(k);if(ie){if(k&&ie.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?$():(C(),this._initPlayerWith(e));return}Pe(ie)}else $()},Q=(F,ie)=>{if(!h()||!this.sourceBuffer)return;let se,ue,Ee;const et=ae=>{window.setTimeout(()=>{h()&&Q(F,ie)},ae)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),et(100);else{const ae=ee(),Ce=E.currentTime;!this.paused&&E.buffered.length>1&&X===Ce&&ae-le>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),X!==Ce&&(X=Ce,le=ae);const de=this._getBufferSizeSec();if(de>30)B(`Buffered ${de} seconds; delaying appendBuffer`),et(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:ae,buf:de}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(pe){if(pe.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),Ee=this.sourceBuffer.buffered.length,Ee!==0&&(se=this.sourceBuffer.buffered.start(0),ue=Ce,ue-se>4&&this.sourceBuffer.remove(se,ue-3)),et(1e3);else throw pe}}},W=()=>{_&&R&&(B([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(k)]),Q(_,function(){_=null,O()}))},te=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),Pe=F=>{h()&&p(te(F),(ie,se)=>{if(h()){if(se/=1e3,_=ie,k=F,o=F.startTS,se){const ue=Math.min(10,F.dur/se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}W()}},()=>this._handleNetworkError())},Lt=F=>{h()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(F),!1)))},ft=F=>{h()&&(e.cachedHeader=F,Q(F,()=>{R=!0,W()}))};n=!0,I.seek(F=>{if(h()){if(N=ee(),!F){$();return}A=F,!s.isNullable(g)||F.startTS>g?Pe(F):(k=F,O())}},g),e.cachedHeader?ft(e.cachedHeader):f(e.headerUrl,ft,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>o},d}_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=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const m=ee();if(this.chunkRateEstimator.addInterval(f,m,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:b}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,c,u=!0;const l=()=>{let h=n.get();if(h&&c&&this.autoQuality){if(u&&h>c&&$i(o)<3e4)return;i(h)}u=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&l(),p},notifySwitch:h=>{const f=ee();h<c&&(o=f),c=h}}}_fetchManifest(e,t,i){this.manifestRequest=vt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(yt).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;je(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((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,c.push(u))}),c.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),c):(i({name:"error",type:"empty_manifest"}),[])};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))},Ps))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Pi{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}}var x;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(x||(x={}));const Rs=[x.PAUSED,x.PLAYING,x.READY],Ns=[x.PAUSED,x.PLAYING,x.READY];class Is{subscription=new s.Subscription;video;videoState=new q(x.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new xe;droppedFramesManager=new Pi;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new zt;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=Fe(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(Te(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=He(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(s.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===x.READY&&this.videoState.setState(x.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(s.combine({zeroTime:this.zeroTime$.pipe(s.filter(s.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(ht(this.video,this.params.desiredState.isLooped,t)).add(Ue(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{const n=a&&s.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(a.to)}},t)).add(s.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Oe(this.video)}createLiveDashPlayer(){const e=new xs({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,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},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:Pt(e.map(({track:l})=>l),{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}),n=a?.id,o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(o||n!==c)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),o||u||n!==c){const l=e.find(({track:d})=>d.id===n)?.representation;s.assertNonNullable(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;s.assertNonNullable(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(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=$t(a.name)??s.videoSizeToQuality(a.video),c=a.bitrate/1e3,u={...a.video};if(!o)continue;const l={id:n,quality:o,bitrate:c,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),s.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(t)return;const o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ns.includes(e)&&(o||c)){this.prepare();return}if(a?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&Rs.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(fe(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const u=a?.from;u&&u===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)})}return;case x.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(x.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(fe(this.params.source.url,u))}return;default:return s.assertNever(e)}}}var K;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(K||(K={}));var be;(function(r){r[r.ActiveLowLatency=0]="ActiveLowLatency",r[r.LiveWithTargetOffset=1]="LiveWithTargetOffset",r[r.LiveForwardBuffering=2]="LiveForwardBuffering",r[r.None=3]="None"})(be||(be={}));var Tt;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Tt||(Tt={}));var oe;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(oe||(oe={}));var L;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(L||(L={}));var Xe;(function(r){r.MP4="mp4",r.WEBM="webm"})(Xe||(Xe={}));var Et;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Et||(Et={}));var Y;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Y||(Y={}));var Qe=(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 Vs=300,Ms=(r,e=Vs)=>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(s.debounceFn(o=>{const c=o[0];if(!c)return;let u,l;c.contentBoxSize&&c.contentBoxSize[0]?(l=c.contentBoxSize[0].blockSize,u=c.contentBoxSize[0].inlineSize):c.contentRect&&(u=c.contentRect.width,l=c.contentRect.height),s.isNonNullable(u)&&s.isNonNullable(l)&&t.next({width:u,height:l})},e));return n.observe(r),()=>n.disconnect()});class ai{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 Ci extends ai{constructor(){super(),this.listeners||ai.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 Di=class{constructor(){Object.defineProperty(this,"signal",{value:new Ci,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&&(Di.prototype[Symbol.toStringTag]="AbortController",Ci.prototype[Symbol.toStringTag]="AbortSignal");function Li(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 Bs(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!Li({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(l,d){let h;d&&d.signal&&(h=d.signal,delete d.signal);const f=new t(l,d);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(u,l)=>{const d=n&&n.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(d.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{d.addEventListener("abort",()=>m(h),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,o(u,l)])}return o(u,l)},Request:n}}const Ct=Li({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xi=Ct?Bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ut=Ct?xi.fetch:window.fetch;Ct?xi.Request:window.Request;const Je=Ct?Di:window.AbortController;var Ot=(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 _s=(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)},Fs=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ri=Fs?_s:window.requestIdleCallback,Os=16;let Ri=!1;try{Ri=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Os}catch(r){console.error(r)}class Us{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;Ri&&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 ni=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};class ce{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 Ni extends ce{}class Hs extends ce{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 js extends ce{parseChildrenBoxes(){return Re(this.content)}}class Ys extends ce{parseChildrenBoxes(){return Re(this.content)}}class Gs extends ce{data;constructor(e){super(e),this.data=this.content}}class $e extends ce{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class qs extends $e{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,u=i<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:u})}}}class zs extends ce{parseChildrenBoxes(){return Re(this.content)}}class Qs extends ce{parseChildrenBoxes(){return Re(this.content)}}var _e;(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"})(_e||(_e={}));class Ws extends $e{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=_e.MONOSCOPIC;break;case 1:this.stereoMode=_e.TOP_BOTTOM;break;case 2:this.stereoMode=_e.LEFT_RIGHT;break;case 3:this.stereoMode=_e.STEREO_CUSTOM;break;case 4:this.stereoMode=_e.RIGHT_LEFT;break}this.cursor+=1}}class Js extends $e{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Xs extends $e{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 Ks extends ce{parseChildrenBoxes(){return Re(this.content)}}class Zs extends $e{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 ea extends ce{parseChildrenBoxes(){return Re(this.content)}}class ta extends ce{parseChildrenBoxes(){return Re(this.content)}}class ia extends $e{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class sa extends ce{parseChildrenBoxes(){return Re(this.content)}}class aa extends $e{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class ra extends $e{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class na extends $e{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const oa={ftyp:Hs,moov:js,moof:Ys,mdat:Gs,sidx:qs,trak:zs,mdia:Ks,mfhd:ia,tkhd:Zs,traf:sa,tfhd:aa,tfdt:ra,trun:na,minf:ea,sv3d:Qs,st3d:Ws,prhd:Js,proj:ta,equi:Xs,unknown:Ni};class ca{createBox(e,t){const i=oa[e];return i?new i(t):new Ni(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Dt.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Dt=new ca;function ot(r,e){const t=new Uint8Array(r.buffer),i=e.split("").map(o=>o.charCodeAt(0));let a=r.byteOffset,n=[];for(;a<t.byteLength;){if(t[a]===i[n.length]?n.push(t[a]):n=[],n.length===4){const c=new DataView(r.buffer,a-7,4).getUint32(0);return a-7+c>r.buffer.byteLength?null:Dt.createBox(e,new DataView(r.buffer,a-7))}a++}return null}function Ut(r,e){const t=[];let i=r.byteOffset;for(;i<r.buffer.byteLength;){const a=ot(new DataView(r.buffer,i,r.buffer.byteLength-i),e);if(a)t.push(a),i=a.source.byteOffset+a.size;else break}return t}function Re(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Dt.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const la=new TextDecoder("ascii"),ua=r=>la.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",da=r=>{const e=Dt.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:L.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,c})},ha=r=>{const e=Ut(r,"mdat"),t=Ut(r,"moof");if(!(e.length&&t.length))return null;const i=t[0],a=e[e.length-1],n=i.source.byteOffset,c=a.source.byteOffset-i.source.byteOffset+a.size;return new DataView(r.buffer,n,c)},fa=(r,e)=>{const t=Ut(r,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),a=t[t.length-1].children.find(u=>u.type==="tfdt"),n=t[t.length-1].children.find(u=>u.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((u,l)=>u+l,0):o=i.defaultSampleDuration*n.sampleCount,(Number(a.baseMediaDecodeTime)+o)/e*1e3},pa=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Et.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ot(r,"sv3d")){e.is3dVideo=!0;const i=ot(r,"st3d");i&&(e.stereoMode=i.stereoMode);const a=ot(r,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=ot(r,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},ma={validateData:ua,parseInit:pa,getIndexRange:()=>{},parseSegments:da,parseFeedableSegmentChunk:ha,getSegmentEndTime:fa};var S;(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"})(S||(S={}));var v;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(v||(v={}));const oi={[S.EBML]:{type:v.Master},[S.EBMLVersion]:{type:v.UnsignedInteger},[S.EBMLReadVersion]:{type:v.UnsignedInteger},[S.EBMLMaxIDLength]:{type:v.UnsignedInteger},[S.EBMLMaxSizeLength]:{type:v.UnsignedInteger},[S.DocType]:{type:v.String},[S.DocTypeVersion]:{type:v.UnsignedInteger},[S.DocTypeReadVersion]:{type:v.UnsignedInteger},[S.Void]:{type:v.Binary},[S.Segment]:{type:v.Master},[S.SeekHead]:{type:v.Master},[S.Seek]:{type:v.Master},[S.SeekID]:{type:v.Binary},[S.SeekPosition]:{type:v.UnsignedInteger},[S.Info]:{type:v.Master},[S.TimestampScale]:{type:v.UnsignedInteger},[S.Duration]:{type:v.Float},[S.Tracks]:{type:v.Master},[S.TrackEntry]:{type:v.Master},[S.Video]:{type:v.Master},[S.Projection]:{type:v.Master},[S.ProjectionType]:{type:v.UnsignedInteger},[S.ProjectionPrivate]:{type:v.Master},[S.Chapters]:{type:v.Master},[S.Cluster]:{type:v.Master},[S.Timestamp]:{type:v.UnsignedInteger},[S.SilentTracks]:{type:v.Master},[S.SilentTrackNumber]:{type:v.UnsignedInteger},[S.Position]:{type:v.UnsignedInteger},[S.PrevSize]:{type:v.UnsignedInteger},[S.SimpleBlock]:{type:v.Binary},[S.BlockGroup]:{type:v.Master},[S.EncryptedBlock]:{type:v.Binary},[S.Attachments]:{type:v.Master},[S.Tags]:{type:v.Master},[S.Cues]:{type:v.Master},[S.CuePoint]:{type:v.Master},[S.CueTime]:{type:v.UnsignedInteger},[S.CueTrackPositions]:{type:v.Master},[S.CueTrack]:{type:v.UnsignedInteger},[S.CueClusterPosition]:{type:v.UnsignedInteger},[S.CueRelativePosition]:{type:v.UnsignedInteger},[S.CueDuration]:{type:v.UnsignedInteger},[S.CueBlockNumber]:{type:v.UnsignedInteger},[S.CueCodecState]:{type:v.UnsignedInteger},[S.CueReference]:{type:v.Master},[S.CueRefTime]:{type:v.UnsignedInteger}},Ii=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=kt(r,t),a=i in oi,n=a?oi[i].type:v.Binary,o=r.getUint8(t);let c=0;o&128?c=1:o&64?c=2:o&32?c=3:o&16?c=4:o&8?c=5:o&4?c=6:o&2?c=7:o&1&&(c=8);const u=new DataView(r.buffer,r.byteOffset+t+1,c-1),l=o&255>>c,d=kt(u),h=l*2**((c-1)*8)+d,f=t+c;let p;return f+h>r.byteLength?p=new DataView(r.buffer,r.byteOffset+f):p=new DataView(r.buffer,r.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},kt=(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 v.SignedInteger:return r.getInt8(0);case v.UnsignedInteger:return kt(r);case v.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case v.String:return new TextDecoder("ascii").decode(r);case v.UTF8:return new TextDecoder("utf-8").decode(r);case v.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case v.Master:return r;case v.Binary:return r;default:s.assertNever(e)}},Ke=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),a=Ii(i);if(!e(a))return;a.type===v.Master&&Ke(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},Sa=r=>{if(r.getUint32(0)!==S.EBML)return!1;let e,t,i;const a=Ii(r);return Ke(a.value,({tag:n,type:o,value:c})=>(n===S.EBMLReadVersion?e=ye(c,o):n===S.DocType?t=ye(c,o):n===S.DocTypeReadVersion&&(i=ye(c,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Vi=[S.Info,S.SeekHead,S.Tracks,S.TrackEntry,S.Video,S.Projection,S.ProjectionType,S.ProjectionPrivate,S.Chapters,S.Cluster,S.Cues,S.Attachments,S.Tags],ba=[S.Timestamp,S.SilentTracks,S.SilentTrackNumber,S.Position,S.PrevSize,S.SimpleBlock,S.BlockGroup,S.EncryptedBlock],ga=r=>{let e,t,i,a,n=!1,o=!1,c=!1,u,l,d=!1;const h=0;return Ke(r,({tag:f,type:p,value:m,valueSize:T})=>{if(f===S.SeekID){const b=ye(m,p);l=kt(b)}else f!==S.SeekPosition&&(l=void 0);return f===S.Segment?(e=m.byteOffset,t=m.byteOffset+T):f===S.Info?n=!0:f===S.SeekHead?o=!0:f===S.TimestampScale?i=ye(m,p):f===S.Duration?a=ye(m,p):f===S.SeekPosition&&l===S.Cues?u=ye(m,p):f===S.Tracks?Ke(m,({tag:b,type:y,value:C})=>b===S.ProjectionType?(d=ye(C,y)===1,!1):!0):n&&o&&Vi.includes(f)&&(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:u,is3dVideo:d,stereoMode:h,projectionType:Et.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ya=r=>{if(s.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},va=(r,e)=>{let t=!1,i=!1;const a=c=>s.isNonNullable(c.time)&&s.isNonNullable(c.position),n=[];let o;return Ke(r,({tag:c,type:u,value:l})=>{switch(c){case S.Cues:t=!0;break;case S.CuePoint:o&&a(o)&&n.push(o),o={};break;case S.CueTime:o&&(o.time=ye(l,u));break;case S.CueTrackPositions:break;case S.CueClusterPosition:o&&(o.position=ye(l,u));break;default:t&&Vi.includes(c)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((c,u)=>{const{time:l,position:d}=c,h=n[u+1];return{status:L.NONE,time:{from:l,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},Ta=r=>{let e=0,t=!1;try{Ke(r,i=>i.tag===S.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ba.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[S.SimpleBlock,S.BlockGroup,S.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Ea={validateData:Sa,parseInit:ga,getIndexRange:ya,parseSegments:va,parseFeedableSegmentChunk:Ta},ka=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)},ci=r=>{if(!r.startsWith("P"))return;const e=(o,c)=>{const u=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(u)?0:u)*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},ze=(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,u)=>s.isNullable(n)?c:s.isNullable(u)?n:n.padStart(parseInt(u,10),"0"))}return t},wa=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],c=n.querySelector("BaseURL")?.textContent?.trim()??"",u=o.children,l=n.getAttribute("type")==="dynamic",d=n.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let f;const p=n.getAttribute("mediaPresentationDuration"),m=o.getAttribute("duration"),b=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)f=ci(p);else if(m){const g=ci(m);s.isNonNullable(g)&&(f=g)}else b&&(f=parseInt(b,10));let y=0;const C=n.getAttribute("profiles")?.split(",")??[],P=C.includes(Tt.WEBM_AS_IN_FFMPEG)||C.includes(Tt.WEBM_AS_IN_SPEC)?Xe.WEBM:Xe.MP4;for(const g of u){const E=g.getAttribute("mimeType"),B=g.getAttribute("codecs"),I=g.getAttribute("contentType")??E?.split("/")[0],R=g.getAttribute("profiles")?.split(",")??[],_=g.querySelectorAll("Representation"),k=g.querySelector("SegmentTemplate");if(I===K.TEXT){for(const A of _){const N=A.getAttribute("id")||"",z=g.getAttribute("lang"),X=A.querySelector("BaseURL")?.textContent?.trim()??"",le=new URL(X||c,e).toString(),$=N.includes("_auto");a[K.TEXT].push({id:N,lang:z,isAuto:$,kind:K.TEXT,url:le})}continue}for(const A of _){const N=A.getAttribute("mimeType")??E,z=A.getAttribute("codecs")??B??"",X=A.getAttribute("contentType")??N?.split("/")[0]??I,le=g.getAttribute("profiles")?.split(",")??[],$=parseInt(A.getAttribute("width")??"",10),O=parseInt(A.getAttribute("height")??"",10),Q=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,W=A.getAttribute("frameRate")??"",te=A.getAttribute("quality")??void 0,Pe=W?ka(W):void 0,Lt=A.getAttribute("id")??(y++).toString(10),ft=X==="video"?`${O}p`:X==="audio"?`${Q}Kbps`:z,F=`${Lt}@${ft}`,ie=A.querySelector("BaseURL")?.textContent?.trim()??"",se=new URL(ie||c,e).toString(),ue=[...C,...R,...le];let Ee;const et=A.querySelector("SegmentBase"),ae=A.querySelector("SegmentTemplate")??k;if(et){const de=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[pe,xt]=de.split("-").map(Ye=>parseInt(Ye,10)),De={from:pe,to:xt},tt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[Rt,pt]=tt?tt.split("-").map(Ye=>parseInt(Ye,10)):[],it=tt?{from:Rt,to:pt}:void 0;Ee={type:oe.BYTE_RANGE,url:se,initRange:De,indexRange:it}}else if(ae){const de={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},pe=parseInt(ae.getAttribute("timescale")??"",10),xt=ae.getAttribute("initialization")??"",De=ae.getAttribute("media"),tt=parseInt(ae.getAttribute("startNumber")??"",10)??1,Rt=ze(xt,de);if(!De)throw new ReferenceError("No media attribute in SegmentTemplate");const pt=ae.querySelectorAll("SegmentTimeline S")??[],it=[];let Ye=0,Nt="",It=0;if(pt.length){let mt=tt,he=0;for(const Ge of pt){const me=parseInt(Ge.getAttribute("d")??"",10),Ne=parseInt(Ge.getAttribute("r")??"",10)||0,St=parseInt(Ge.getAttribute("t")??"",10);he=Number.isFinite(St)?St:he;const Vt=me/pe*1e3,ji=he/pe*1e3;for(let bt=0;bt<Ne+1;bt++){const Yi=ze(De,{...de,segmentNumber:mt.toString(10),segmentTime:(he+bt*me).toString(10)}),Xt=(ji??0)+bt*Vt,Gi=Xt+Vt;mt++,it.push({time:{from:Xt,to:Gi},url:Yi})}he+=(Ne+1)*me,Ye+=(Ne+1)*Vt}It=he/pe*1e3,Nt=ze(De,{...de,segmentNumber:mt.toString(10),segmentTime:he.toString(10)})}else if(s.isNonNullable(f)){const he=parseInt(ae.getAttribute("duration")??"",10)/pe*1e3,Ge=Math.ceil(f/he);let me=0;for(let Ne=1;Ne<Ge;Ne++){const St=ze(De,{...de,segmentNumber:Ne.toString(10),segmentTime:me.toString(10)});it.push({time:{from:me,to:me+he},url:St}),me+=he}It=me,Nt=ze(De,{...de,segmentNumber:Ge.toString(10),segmentTime:me.toString(10)})}const Hi={time:{from:It,to:1/0},url:Nt};Ee={type:oe.TEMPLATE,baseUrl:se,segmentTemplateUrl:De,initUrl:Rt,totalSegmentsDurationMs:Ye,segments:it,nextSegmentBeyondManifest:Hi,timescale:pe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!N)continue;const Ce={video:K.VIDEO,audio:K.AUDIO,text:K.TEXT}[X];Ce&&a[Ce].push({id:F,kind:Ce,segmentReference:Ee,profiles:ue,duration:f,bitrate:Q,mime:N,codecs:z,width:$,height:O,fps:Pe,quality:te})}}return{dynamic:l,liveAvailabilityStartTime:h,duration:f,container:P,representations:a}},Aa=({id:r,width:e,height:t,bitrate:i,fps:a,quality:n})=>{const o=(n?$t(n):void 0)??s.videoSizeToQuality({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a}},$a=({id:r,bitrate:e})=>({id:r,bitrate:e}),Pa=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},Ca=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),li=r=>"size"in r,qe=r=>r.type===oe.TEMPLATE,Ht=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);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=[];subscription=new s.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Je;destroyAbortController=new Je;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:c,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:d}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=l,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=c,this.isActiveLowLatency=u,this.isLive=!!d?.dynamic,this.container=i,i){case Xe.MP4:this.containerParser=ma;break;case Xe.WEBM:this.containerParser=Ea;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 Us(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,ni(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.isLive||(i.forEach(o=>o.status=L.NONE),this.pruneBuffer(n,1/0,!0)),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 Je,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(l=>e>=l.time.from&&e<l.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=Qe(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ni(this.sourceBuffer.buffered)>=this.bufferLimit){const l=Qe(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(i,t.segmentReference.type,n),c.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(c.includes(a))l="high";else{const d=c.at(0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(c,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===L.FED&&!c.length&&Qe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=i.at(-1);u&&u.status===L.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}searchGaps(e,t){this.gaps=[];let i=0;const a=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+a}),i=n.time.to;s.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[];let n=0,o=t.length-1;do a.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,this.isActiveLowLatency()?[a[0]]:a}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 u=e.find(h=>h.id===c);u&&this.representations.set(c,u);const l=this.representations.get(c);if(!l||!qe(l.segmentReference))return;const d=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,d)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);s.assertNonNullable(i);const a=this.segments.get(t);s.assertNonNullable(a,"No segments for starting representation");const n=this.initData.get(t);if(s.assertNonNullable(n,"No init buffer 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||!qe(t.segmentReference))return;const i=t.segmentReference.segments.map(c=>({...c,status:L.NONE,size:void 0})),a=this.segments.get(t.id)??[],n=a.at(-1)?.time.to??0,o=i?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,c)}else{const c=i.slice(o+1);this.segments.set(t.id,[...a,...c])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!qe(i))return;const a=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=ze(i.segmentTemplateUrl,{segmentTime:a}),o=this.segments.get(t.id)??[],c=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));c&&(c.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:L.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}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:h,time:{from:f,to:p}},m)=>{const T=f<=i&&p>=i,b=f>i||T||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&f<=i+y||p<=i+y;return(h===L.NONE||h===L.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!Ot(this.sourceBuffer.buffered,i))&&b&&C});if(a===-1)return[];if(t!==oe.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,c=0;const u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=l||c<=d);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,c+=f.time.to+1-f.time.from,f.status===L.NONE||f.status===L.PARTIALLY_EJECTED)u.push(f);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===oe.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=L.DOWNLOADING;const a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);const{range:n,url:o,signal:c,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&c&&(await s.abortable(c,async function*(){const d=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted&&this.abortActiveSegments([e]));try{const d=await this.fetcher.fetch(o,{range:n,signal:c,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,c),a.segment.status=L.DOWNLOADED,this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){if(!Ht(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=L.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:a,url:n,signal:o,onProgress:c}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await s.abortable(o,async function*(){const u=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:a,onProgress:c,signal:o,priority:i}),this.failedDownloads=0}catch(u){if(!Ht(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}}prepareByteRangeFetchSegmentParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:a,signal:n,onProgress:(u,l)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:l,signal:n,onSegmentAppendFailed:o,globalFrom:a?a.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const a=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},c=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:d,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});c.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:a,signal:n,onProgress:l,onProgressTasks:c}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&s.isNonNullable(i)&&(t=Qe(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})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:a,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const c of this.activeSegments){const{segment:u}=c;if(c.representationId===t){if(n.aborted){a();continue}if(c.loadedBytes=i,c.loadedBytes>c.feedingBytes){const l=new DataView(e.buffer,e.byteOffset+c.feedingBytes,c.loadedBytes-c.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(l);d?.byteLength&&(u.status=L.PARTIALLY_FED,c.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),c.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const c=this.representations.get(t);if(!c)return;const u=c.segmentReference.type,l=e.byteLength;for(const d of this.activeSegments){const{segment:h}=d,f=u===oe.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:l;if(d.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const T=f?h.byte.from-i:0,b=f?h.byte.to-i:e.byteLength,y=T<a,C=b<=a;if(h.status===L.DOWNLOADING&&y&&C){h.status=L.DOWNLOADED;const P=new DataView(e.buffer,e.byteOffset+T,p);this.sourceBufferTaskQueue.append(P,n).then(g=>g&&!n.aborted?this.onSegmentFullyAppended(d,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(d.loadedBytes=Math.min(p,a-T),d.loadedBytes>d.feedingBytes)){const P=new DataView(e.buffer,e.byteOffset+T+d.feedingBytes,d.loadedBytes-d.feedingBytes),g=d.loadedBytes===p?P:this.containerParser.parseFeedableSegmentChunk(P);g?.byteLength&&(h.status=L.PARTIALLY_FED,d.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,n).then(E=>{if(n.aborted)o();else if(E)d.fedBytes+=g.byteLength,d.fedBytes===p&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=L.FED,li(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const a of this.segments.get(i.id)??[])a.status===L.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=L.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===L.PARTIALLY_FED||e.status===L.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=L.NONE),e.status=L.PARTIALLY_EJECTED):e.status=L.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=ri(()=>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(u=>setTimeout(u,c))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async c=>{if(!c)return;const{init:u,dataView:l,segments:d}=c,h=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,h);let f=d;this.isLive&&qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).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 u=l=>{n=Math.min(n,l.time.from),o=Math.max(o,l.time.to);const d=li(l)?l.size??0:l.byte.to-l.byte.from;a+=d};for(const l of this.segments.values())for(const d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status===L.FED&&u(d)}if(c=isFinite(n)&&isFinite(o),!c){a=0,n=1/0,o=-1/0;for(const l of this.segments.values())for(const d of l){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status===L.FED&&u(d)}}if(c=isFinite(n)&&isFinite(o),!c)for(let l=0;l<this.sourceBuffer.buffered.length;l++){const d=this.sourceBuffer.buffered.start(l)*1e3,h=this.sourceBuffer.buffered.end(l)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===L.NONE&&Math.round(p.time.from)<=Math.round(d)&&Math.round(p.time.to)>=Math.round(h)){n=d,o=h;break}}if(c=isFinite(n)&&isFinite(o),!c&&i){a=0,n=1/0,o=-1/0;const l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const h of d)h.time.from>e+l&&h.status===L.FED&&u(h)}return c=isFinite(n)&&isFinite(o),c?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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=ri(()=>{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!==L.FED&&n!==L.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),c=Math.ceil(a.time.to),u=e.some(d=>d.from-t<=o&&d.to+t>=c),l=e.filter(d=>o>=d.from-t&&o<=d.to+t||c>=d.from-t&&c<=d.to+t);u||(l.length===1?a.status=L.PARTIALLY_EJECTED:a.status=L.NONE)}}}var jt=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Da=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}},We;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(We||(We={}));class La{throughputEstimator;requestQuic;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);abortAllController=new Je;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}=Da(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=s.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=jt(t));const i=yield ut(t,{signal:this.abortAllController.signal}).catch(st);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=s.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?We.HEADER:We.PARAM,range:i,onProgress:a,priority:n="auto",signal:o,measureThroughput:c=!0,isLowLatency:u=!1}={}){let l=e;const d=new Headers;if(i)switch(t){case We.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case We.PARAM:{const R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:s.assertNever(t)}this.requestQuic&&(l=jt(l));let h=this.abortAllController.signal,f;if(o){const R=new Je;if(f=s.merge(s.fromEvent(this.abortAllController.signal,"abort"),s.fromEvent(o,"abort")).subscribe(()=>{try{R.abort()}catch(_){st(_)}}),this.abortAllController.signal.aborted||o.aborted)try{R.abort()}catch(_){st(_)}h=R.signal}const p=s.now(),m=yield ut(l,{priority:n,headers:d,signal:h}).catch(st),T=s.now();if(!m)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(T-p),!m.ok||!m.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!c)return f?.unsubscribe(),m.arrayBuffer();const[b,y]=m.body.tee(),C=b.getReader();c&&this.throughputEstimator?.trackStream(y,u);let P=0,g=new Uint8Array(0),E=!1;const B=R=>{f?.unsubscribe(),E=!0,st(R)},I=s.abortable(h,async function*({done:R,value:_}){if(P===0&&this.lastRequestFirstBytes$.next(s.now()-p),h.aborted){f?.unsubscribe();return}if(!R&&_){const k=new Uint8Array(g.length+_.length);k.set(g),k.set(_,g.length),g=k,P+=_.byteLength,a?.(new DataView(g.buffer),P),yield C?.read().then(I,B)}}.bind(this));return yield C?.read().then(I,B),f?.unsubscribe(),E?null:g.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:a}=e;switch(a){case oe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case oe.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!==oe.BYTE_RANGE)return null;const{from:a,to:n}=e.initRange;let o=a,c=n,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=n+1===l,u&&(o=Math.min(l,a),c=Math.max(d,n))),o=Math.min(o,0);const h=yield this.fetch(e.url,{range:{from:o,to:c},priority:i,measureThroughput:!1});if(!h)return null;const f=new DataView(h,a-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let T;if(u)T=new DataView(h,m.from-o,m.to-m.from+1);else{const y=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!y)return null;T=new DataView(y)}const b=t.parseSegments(T,p,m);return{init:p,dataView:new DataView(h),segments:b}}.bind(this));fetchTemplateRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==oe.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:L.NONE,size:void 0})),dataView:new DataView(a)}:null}.bind(this))}const st=r=>{if(!Ht(r))throw r},Yt=1e3,wt=(r,e,t)=>t*e+(1-t)*r,Mi=(r,e)=>r.reduce((t,i)=>t+i,0)/e,xa=(r,e,t,i)=>{let a=0,n=t;const o=Mi(r,e),c=e<i?e:i;for(let u=0;u<c;u++)r[n]>o?a++:a--,n=(r.length+n-1)%r.length;return Math.abs(a)===c};class Wt{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 Ra extends Wt{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=wt(this.slow,e,this.params.emaAlphaSlow),this.fast=wt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Na extends Wt{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Mi(this.pastMeasures,this.takenMeasures);this.emaSmoothed=wt(this.emaSmoothed,e,this.params.emaAlpha);const i=xa(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Ia extends Wt{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?wt(this.smoothed,e,this.params.emaAlpha):e}}class Gt{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ra({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Na({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ia({initial:e,label:"liveEdgeDelay",...t})}}const Va=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)},Ie=()=>window.ManagedMediaSource||window.MediaSource,Bi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Ma=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Ba=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,di=["timeupdate","progress","play","seeked","stalled","waiting"];var ne;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(ne||(ne={}));let _a=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new s.Subscription;representationSubscription=new s.Subscription;fetcher;state$=new q(ne.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);livePositionFromPlayer$=new s.ValueSubject(0);liveEstimatedDelay;waitingEventInterval;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new s.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Je;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new La({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=s.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=fe(t,i,J.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ne.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(ne.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 null;let t;try{t=wa(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)&&Ie()?.isTypeSupported?.(`${n}; codecs="${o}"`)||a===K.TEXT);return t.dynamic&&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);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=fe(this.manifestUrlString,t,J.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(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,i){s.assertNonNullable(this.manifest),s.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ne.REPRESENTATIOS_READY);const a=p=>{this.representationSubscription.add(s.fromEvent(p,"error").pipe(s.filter(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ba():new MediaSource;const n=document.createElement("source");if(a(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),this.tuning.useManagedMediaSource&&Bi())if(i){const p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const o={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new ui(K.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,o),this.bufferManagers=[this.videoBufferManager],s.isNonNullable(t)&&(this.audioBufferManager=new ui(K.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,o),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(p=>{if(this.element?.paused){const m=Zt(this.manifestUrlString,J.DASH_CMAF_OFFSET_P);this.manifestUrlString=fe(this.manifestUrlString,m+Yt,J.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(s.merge(...di.map(p=>s.fromEvent(this.element,p))).pipe(s.map(p=>this.element?Qe(this.element.buffered,this.element.currentTime*1e3):0),s.filterChanged(),s.filter(p=>!!p),s.tap(p=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(s.filter(m=>this.isActiveLowLatency&&!!m)).subscribe(m=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(m=>{if(!this.isActiveLowLatency)return;const T=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,C=m-T;let P=1+Math.sign(C)*y;Math.abs(C)<b?P=1:Math.abs(C)>b*2&&(P=1+Math.sign(C)*y*2),Va(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let T=0;if(m){const b=(this.element?.currentTime??0)*1e3;T=Math.min(...this.bufferManagers.map(C=>C.getLiveSegmentsToLoadState(this.manifest)?.to??0))-b}T&&this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let p=0;this.representationSubscription.add(s.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:m,bufferLength:T})=>{if(s.assertNonNullable(this.element),this.isUpdatingLive)return;const b=this.element.playbackRate,y=Zt(this.manifestUrlString,J.DASH_CMAF_OFFSET_P),C=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(C,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),g=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,B=this.isActiveLowLatency?T:m;let I=be.None;if(this.isActiveLowLatency?I=be.ActiveLowLatency:B<P+E&&B>=P?I=be.LiveWithTargetOffset:y!==0&&B<P&&(I=be.LiveForwardBuffering),isFinite(m)&&(p=m>p?m:p),I===be.LiveForwardBuffering||I===be.LiveWithTargetOffset){const R=p-(P+g),_=this.normolizeLiveOffset(Math.trunc(y+R/b)),k=Math.abs(_-y);let A;!m||k<=this.tuning.dashCmafLive.offsetCalculationError?A=y:_>0&&k>this.tuning.dashCmafLive.offsetCalculationError?A=_:A=0,this.manifestUrlString=fe(this.manifestUrlString,A,J.DASH_CMAF_OFFSET_P)}I!==be.None&&I!==be.ActiveLowLatency&&(p=0,this.updateLive())}))}const c=s.merge(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(s.map(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),u=s.merge(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(s.map(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(s.merge(this.forceEnded$,s.combine({allBuffersFull:c,someBufferEnded:u}).pipe(s.filter(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(s.merge(...this.bufferManagers.map(p=>p.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(p=>this.source?.addEventListener("sourceopen",p)));const l=this.manifest.duration??0,d=(p,m)=>Math.max(p,m.duration??0),h=this.manifest.representations.audio.reduce(d,l),f=this.manifest.representations.video.reduce(d,l);(h||f)&&(this.source.duration=Math.max(h,f)/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(ne.REPRESENTATIOS_READY)}.bind(this));initBuffer(){s.assertNonNullable(this.element),this.state$.setState(ne.RUNNING),this.subscription.add(s.merge(...di.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&&Ot(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){return{[K.VIDEO]:this.videoBufferManager,[K.AUDIO]:this.audioBufferManager,[K.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),Ot(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?.querySelectorAll("source").forEach(e=>e.remove()),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(ne.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(),window.clearInterval(this.waitingEventInterval),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:s.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,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):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(a)&&(this.element.currentTime=a/1e3)}}};class Fa{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Oa{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 Ua=`#define GLSLIFY 1
37
+ `}),k}return l?.recordSwitch(R),R};var Te=r=>new URL(r).hostname;const ii=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 je=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!ii(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return ii(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function ee(){return s.now()}function $i(r){return ee()-r}function si(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,u=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let l=o.indexOf("?")>-1?"&":"?";return u&&(o+=l+"lowLat=1",l="&"),c&&(o+=l+"_rnd="+Math.floor(999999999*Math.random())),o}}}function Ts(r,e,t){const i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function vt(r,e,t,i){const a=window.XMLHttpRequest;let n,o,c,u=!1,l=0,d,h,f=!1,p="arraybuffer",m=7e3,T=2e3,b=()=>{if(u)return;s.assertNonNullable(d);const N=$i(d);let z;if(N<T){z=T-N,setTimeout(b,z);return}T*=2,T>m&&(T=m),o&&o.abort(),o=new a,_()};const g=N=>(n=N,A),C=N=>(h=N,A),P=()=>(p="json",A),y=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,h&&h(),t&&t()}},E=N=>(f=N,A),_=()=>{d=ee(),o=new a,o.open("get",r);let N=0,z,X=0;const le=()=>(s.assertNonNullable(d),Math.max(d,Math.max(z||0,X||0)));if(n&&o.addEventListener("progress",$=>{const O=ee();n.updateChunk&&$.loaded>N&&(n.updateChunk(le(),$.loaded-N),N=$.loaded,z=O)}),c&&(o.timeout=c,o.addEventListener("timeout",()=>y())),o.addEventListener("load",()=>{if(u)return;s.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const O=o.response.byteLength-N;O&&n.updateChunk&&n.updateChunk(le(),O)}o.responseType==="json"&&!Object.values(o.response).length?y():(h&&h(),e(o.response))}else y()}),o.addEventListener("error",()=>{y()}),f){const $=()=>{s.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(X=ee(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),A},A={withBitrateReporting:g,withParallel:E,withJSONResponse:P,withRetryCount:N=>(l=N,A),withRetryInterval:(N,z)=>(s.isNonNullable(N)&&(T=N),s.isNonNullable(z)&&(m=z),A),withTimeout:N=>(c=N,A),withFinally:C,send:_,abort:()=>{o&&(o.abort(),o=void 0),u=!0,h&&h()}};return A}const Es=100,ks=2e3,ws=500;let As=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-ws;if(t-e>ks){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 u=n.bytes*o/c;a+=u,n.start=t,n.bytes-=u}}}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>Es&&(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 $s{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=ee(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},c=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=vt(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=ee()}_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=ee();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 yt=1e4,Bt=3,Ps=6e4,Cs=10,Ds=1,Ls=500;class xs{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 As(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=si(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=si(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=()=>{Ts(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 $s(Bt,yt,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,u=null,l=null,d=!1;const h=()=>{const y=n&&(!d||d===this.rep);return y||t("Not running!"),y},f=(y,E,_)=>{u&&u.abort(),u=vt(this.urlResolver.resolve(y,!1),E,_,()=>this._retryCallback()).withTimeout(yt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bt).withFinally(()=>{u=null}).send()},p=(y,E,_)=>{s.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,_,()=>this._retryCallback()).withFinally(()=>{c=null}).send()},m=y=>{const E=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),i.playbackRate=y)},T=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const _=ee()-1e4;let V=0;for(let M=0;M<this.bufferStates.length;M++){const k=this.bufferStates[M];y=Math.min(y,k.buf),k.ts<_&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${y} drop=${V} jitter=${this.sourceJitter}`);let R=y-Ds;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?m(1.15):R>1?m(1.1):R>.3?m(1.05):m(1)}},g=y=>{let E;const _=()=>E&&E.start?E.start.length:0,V=$=>E.start[$]/1e3,R=$=>E.dur[$]/1e3,M=$=>E.fragIndex+$,k=($,O)=>({chunkIdx:M($),startTS:V($),dur:R($),discontinuity:O}),A=()=>{let $=0;if(E&&E.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=O;this.sourceJitter>1&&(W+=this.sourceJitter-1);let te=E.dur.length-1;for(;te>=0&&(W-=E.dur[te],!(W<=0));--te);$=Math.min(te,E.dur.length-1-Q),$=Math.max($,0)}return k($,!0)},N=$=>{const O=_();if(!(O<=0)){if(s.isNonNullable($)){for(let Q=0;Q<O;Q++)if(V(Q)>$)return k(Q)}return A()}},z=$=>{const O=_(),Q=$?$.chunkIdx+1:0,W=Q-E.fragIndex;if(!(O<=0)){if(!$||W<0||W-O>Cs)return t(`Resync: offset=${W} bChunks=${O} chunk=`+JSON.stringify($)),A();if(!(W>=O))return k(Q-E.fragIndex,!1)}},X=($,O,Q)=>{l&&l.abort(),l=vt(this.urlResolver.resolve($,!0,this.lowLatency),O,Q,()=>this._retryCallback()).withTimeout(yt).withRetryCount(Bt).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,O)=>{X(y,Q=>{if(!h())return;E=Q;const W=!!E.lowLatency;W!==this.lowLatency&&T(W);let te=0;for(let Pe=0;Pe<E.dur.length;++Pe)te+=E.dur[Pe];te>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(N(O))},()=>this._handleNetworkError())},nextChunk:z}},C=()=>{n=!1,c&&c.abort(),u&&u.abort(),l&&l.abort(),s.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:y=>{const{videoElement:E,logger:_}=this.params;let V=g(e.jidxUrl),R,M,k,A,N=0,z,X,le;const $=()=>{z&&(clearTimeout(z),z=void 0);const F=Math.max(Ls,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=N+F,se=ee(),ue=Math.min(1e4,ie-se);N=se;const Ee=()=>{l||h()&&V.seek(()=>{h()&&(N=ee(),O(),$())})};ue>0?z=window.setTimeout(()=>{this.paused?$():Ee()},ue):Ee()},O=()=>{let F;for(;F=V.nextChunk(A);)A=F,Lt(F);const ie=V.nextChunk(k);if(ie){if(k&&ie.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?$():(C(),this._initPlayerWith(e));return}Pe(ie)}else $()},Q=(F,ie)=>{if(!h()||!this.sourceBuffer)return;let se,ue,Ee;const et=ae=>{window.setTimeout(()=>{h()&&Q(F,ie)},ae)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),et(100);else{const ae=ee(),Ce=E.currentTime;!this.paused&&E.buffered.length>1&&X===Ce&&ae-le>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),X!==Ce&&(X=Ce,le=ae);const de=this._getBufferSizeSec();if(de>30)_(`Buffered ${de} seconds; delaying appendBuffer`),et(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:ae,buf:de}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(pe){if(pe.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),Ee=this.sourceBuffer.buffered.length,Ee!==0&&(se=this.sourceBuffer.buffered.start(0),ue=Ce,ue-se>4&&this.sourceBuffer.remove(se,ue-3)),et(1e3);else throw pe}}},W=()=>{M&&R&&(_([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(k)]),Q(M,function(){M=null,O()}))},te=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),Pe=F=>{h()&&p(te(F),(ie,se)=>{if(h()){if(se/=1e3,M=ie,k=F,o=F.startTS,se){const ue=Math.min(10,F.dur/se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}W()}},()=>this._handleNetworkError())},Lt=F=>{h()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(F),!1)))},ft=F=>{h()&&(e.cachedHeader=F,Q(F,()=>{R=!0,W()}))};n=!0,V.seek(F=>{if(h()){if(N=ee(),!F){$();return}A=F,!s.isNullable(y)||F.startTS>y?Pe(F):(k=F,O())}},y),e.cachedHeader?ft(e.cachedHeader):f(e.headerUrl,ft,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>o},d}_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=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const m=ee();if(this.chunkRateEstimator.addInterval(f,m,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:b}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,c,u=!0;const l=()=>{let h=n.get();if(h&&c&&this.autoQuality){if(u&&h>c&&$i(o)<3e4)return;i(h)}u=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&l(),p},notifySwitch:h=>{const f=ee();h<c&&(o=f),c=h}}}_fetchManifest(e,t,i){this.manifestRequest=vt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(yt).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;je(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((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,c.push(u))}),c.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),c):(i({name:"error",type:"empty_manifest"}),[])};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))},Ps))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Pi{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}}var x;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(x||(x={}));const Rs=[x.PAUSED,x.PLAYING,x.READY],Ns=[x.PAUSED,x.PLAYING,x.READY];class Is{subscription=new s.Subscription;video;videoState=new q(x.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new xe;droppedFramesManager=new Pi;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new zt;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=Fe(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(Te(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=He(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(s.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===x.READY&&this.videoState.setState(x.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===I.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(s.combine({zeroTime:this.zeroTime$.pipe(s.filter(s.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(ht(this.video,this.params.desiredState.isLooped,t)).add(Ue(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{const n=a&&s.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(a.to)}},t)).add(s.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Oe(this.video)}createLiveDashPlayer(){const e=new xs({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,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},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:Pt(e.map(({track:l})=>l),{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}),n=a?.id,o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(o||n!==c)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),o||u||n!==c){const l=e.find(({track:d})=>d.id===n)?.representation;s.assertNonNullable(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;s.assertNonNullable(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(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=$t(a.name)??s.videoSizeToQuality(a.video),c=a.bitrate/1e3,u={...a.video};if(!o)continue;const l={id:n,quality:o,bitrate:c,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),s.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(t)return;const o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ns.includes(e)&&(o||c)){this.prepare();return}if(a?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&Rs.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(fe(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const u=a?.from;u&&u===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)})}return;case x.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(x.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(fe(this.params.source.url,u))}return;default:return s.assertNever(e)}}}var K;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(K||(K={}));var be;(function(r){r[r.ActiveLowLatency=0]="ActiveLowLatency",r[r.LiveWithTargetOffset=1]="LiveWithTargetOffset",r[r.LiveForwardBuffering=2]="LiveForwardBuffering",r[r.None=3]="None"})(be||(be={}));var Tt;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Tt||(Tt={}));var oe;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(oe||(oe={}));var L;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(L||(L={}));var Xe;(function(r){r.MP4="mp4",r.WEBM="webm"})(Xe||(Xe={}));var Et;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Et||(Et={}));var Y;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Y||(Y={}));var Qe=(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 Vs=300,Bs=(r,e=Vs)=>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(s.debounceFn(o=>{const c=o[0];if(!c)return;let u,l;c.contentBoxSize&&c.contentBoxSize[0]?(l=c.contentBoxSize[0].blockSize,u=c.contentBoxSize[0].inlineSize):c.contentRect&&(u=c.contentRect.width,l=c.contentRect.height),s.isNonNullable(u)&&s.isNonNullable(l)&&t.next({width:u,height:l})},e));return n.observe(r),()=>n.disconnect()});class ai{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 Ci extends ai{constructor(){super(),this.listeners||ai.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 Di=class{constructor(){Object.defineProperty(this,"signal",{value:new Ci,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&&(Di.prototype[Symbol.toStringTag]="AbortController",Ci.prototype[Symbol.toStringTag]="AbortSignal");function Li(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 Ms(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!Li({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(l,d){let h;d&&d.signal&&(h=d.signal,delete d.signal);const f=new t(l,d);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(u,l)=>{const d=n&&n.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(d.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{d.addEventListener("abort",()=>m(h),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,o(u,l)])}return o(u,l)},Request:n}}const Ct=Li({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xi=Ct?Ms({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ut=Ct?xi.fetch:window.fetch;Ct?xi.Request:window.Request;const Je=Ct?Di:window.AbortController;var Ot=(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 _s=(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)},Fs=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ri=Fs?_s:window.requestIdleCallback,Os=16;let Ri=!1;try{Ri=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Os}catch(r){console.error(r)}class Us{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;Ri&&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 ni=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};class ce{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 Ni extends ce{}class Hs extends ce{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 js extends ce{parseChildrenBoxes(){return Re(this.content)}}class Ys extends ce{parseChildrenBoxes(){return Re(this.content)}}class Gs extends ce{data;constructor(e){super(e),this.data=this.content}}class $e extends ce{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class qs extends $e{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,u=i<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:c,SAPDeltaTime:u})}}}class zs extends ce{parseChildrenBoxes(){return Re(this.content)}}class Qs extends ce{parseChildrenBoxes(){return Re(this.content)}}var _e;(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"})(_e||(_e={}));class Ws extends $e{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=_e.MONOSCOPIC;break;case 1:this.stereoMode=_e.TOP_BOTTOM;break;case 2:this.stereoMode=_e.LEFT_RIGHT;break;case 3:this.stereoMode=_e.STEREO_CUSTOM;break;case 4:this.stereoMode=_e.RIGHT_LEFT;break}this.cursor+=1}}class Js extends $e{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Xs extends $e{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 Ks extends ce{parseChildrenBoxes(){return Re(this.content)}}class Zs extends $e{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 ea extends ce{parseChildrenBoxes(){return Re(this.content)}}class ta extends ce{parseChildrenBoxes(){return Re(this.content)}}class ia extends $e{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class sa extends ce{parseChildrenBoxes(){return Re(this.content)}}class aa extends $e{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class ra extends $e{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class na extends $e{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const oa={ftyp:Hs,moov:js,moof:Ys,mdat:Gs,sidx:qs,trak:zs,mdia:Ks,mfhd:ia,tkhd:Zs,traf:sa,tfhd:aa,tfdt:ra,trun:na,minf:ea,sv3d:Qs,st3d:Ws,prhd:Js,proj:ta,equi:Xs,unknown:Ni};class ca{createBox(e,t){const i=oa[e];return i?new i(t):new Ni(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Dt.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Dt=new ca;function ot(r,e){const t=new Uint8Array(r.buffer),i=e.split("").map(o=>o.charCodeAt(0));let a=r.byteOffset,n=[];for(;a<t.byteLength;){if(t[a]===i[n.length]?n.push(t[a]):n.length&&(n=[],a--),n.length===4){const c=new DataView(r.buffer,a-7,4).getUint32(0);return a-7+c>r.buffer.byteLength?null:Dt.createBox(e,new DataView(r.buffer,a-7))}a++}return null}function Ut(r,e){const t=[];let i=r.byteOffset;for(;i<r.buffer.byteLength;){const a=ot(new DataView(r.buffer,i,r.buffer.byteLength-i),e);if(a)t.push(a),i=a.source.byteOffset+a.size;else break}return t}function Re(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Dt.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const la=new TextDecoder("ascii"),ua=r=>la.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",da=r=>{const e=Dt.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:L.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,c})},ha=r=>{const e=Ut(r,"mdat"),t=Ut(r,"moof");if(!(e.length&&t.length))return null;const i=t[0],a=e[e.length-1],n=i.source.byteOffset,c=a.source.byteOffset-i.source.byteOffset+a.size;return new DataView(r.buffer,n,c)},fa=(r,e)=>{const t=Ut(r,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),a=t[t.length-1].children.find(u=>u.type==="tfdt"),n=t[t.length-1].children.find(u=>u.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((u,l)=>u+l,0):o=i.defaultSampleDuration*n.sampleCount,(Number(a.baseMediaDecodeTime)+o)/e*1e3},pa=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Et.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ot(r,"sv3d")){e.is3dVideo=!0;const i=ot(r,"st3d");i&&(e.stereoMode=i.stereoMode);const a=ot(r,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=ot(r,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},ma={validateData:ua,parseInit:pa,getIndexRange:()=>{},parseSegments:da,parseFeedableSegmentChunk:ha,getSegmentEndTime:fa};var S;(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"})(S||(S={}));var v;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(v||(v={}));const oi={[S.EBML]:{type:v.Master},[S.EBMLVersion]:{type:v.UnsignedInteger},[S.EBMLReadVersion]:{type:v.UnsignedInteger},[S.EBMLMaxIDLength]:{type:v.UnsignedInteger},[S.EBMLMaxSizeLength]:{type:v.UnsignedInteger},[S.DocType]:{type:v.String},[S.DocTypeVersion]:{type:v.UnsignedInteger},[S.DocTypeReadVersion]:{type:v.UnsignedInteger},[S.Void]:{type:v.Binary},[S.Segment]:{type:v.Master},[S.SeekHead]:{type:v.Master},[S.Seek]:{type:v.Master},[S.SeekID]:{type:v.Binary},[S.SeekPosition]:{type:v.UnsignedInteger},[S.Info]:{type:v.Master},[S.TimestampScale]:{type:v.UnsignedInteger},[S.Duration]:{type:v.Float},[S.Tracks]:{type:v.Master},[S.TrackEntry]:{type:v.Master},[S.Video]:{type:v.Master},[S.Projection]:{type:v.Master},[S.ProjectionType]:{type:v.UnsignedInteger},[S.ProjectionPrivate]:{type:v.Master},[S.Chapters]:{type:v.Master},[S.Cluster]:{type:v.Master},[S.Timestamp]:{type:v.UnsignedInteger},[S.SilentTracks]:{type:v.Master},[S.SilentTrackNumber]:{type:v.UnsignedInteger},[S.Position]:{type:v.UnsignedInteger},[S.PrevSize]:{type:v.UnsignedInteger},[S.SimpleBlock]:{type:v.Binary},[S.BlockGroup]:{type:v.Master},[S.EncryptedBlock]:{type:v.Binary},[S.Attachments]:{type:v.Master},[S.Tags]:{type:v.Master},[S.Cues]:{type:v.Master},[S.CuePoint]:{type:v.Master},[S.CueTime]:{type:v.UnsignedInteger},[S.CueTrackPositions]:{type:v.Master},[S.CueTrack]:{type:v.UnsignedInteger},[S.CueClusterPosition]:{type:v.UnsignedInteger},[S.CueRelativePosition]:{type:v.UnsignedInteger},[S.CueDuration]:{type:v.UnsignedInteger},[S.CueBlockNumber]:{type:v.UnsignedInteger},[S.CueCodecState]:{type:v.UnsignedInteger},[S.CueReference]:{type:v.Master},[S.CueRefTime]:{type:v.UnsignedInteger}},Ii=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=kt(r,t),a=i in oi,n=a?oi[i].type:v.Binary,o=r.getUint8(t);let c=0;o&128?c=1:o&64?c=2:o&32?c=3:o&16?c=4:o&8?c=5:o&4?c=6:o&2?c=7:o&1&&(c=8);const u=new DataView(r.buffer,r.byteOffset+t+1,c-1),l=o&255>>c,d=kt(u),h=l*2**((c-1)*8)+d,f=t+c;let p;return f+h>r.byteLength?p=new DataView(r.buffer,r.byteOffset+f):p=new DataView(r.buffer,r.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},kt=(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 v.SignedInteger:return r.getInt8(0);case v.UnsignedInteger:return kt(r);case v.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case v.String:return new TextDecoder("ascii").decode(r);case v.UTF8:return new TextDecoder("utf-8").decode(r);case v.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case v.Master:return r;case v.Binary:return r;default:s.assertNever(e)}},Ke=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),a=Ii(i);if(!e(a))return;a.type===v.Master&&Ke(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},Sa=r=>{if(r.getUint32(0)!==S.EBML)return!1;let e,t,i;const a=Ii(r);return Ke(a.value,({tag:n,type:o,value:c})=>(n===S.EBMLReadVersion?e=ye(c,o):n===S.DocType?t=ye(c,o):n===S.DocTypeReadVersion&&(i=ye(c,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Vi=[S.Info,S.SeekHead,S.Tracks,S.TrackEntry,S.Video,S.Projection,S.ProjectionType,S.ProjectionPrivate,S.Chapters,S.Cluster,S.Cues,S.Attachments,S.Tags],ba=[S.Timestamp,S.SilentTracks,S.SilentTrackNumber,S.Position,S.PrevSize,S.SimpleBlock,S.BlockGroup,S.EncryptedBlock],ga=r=>{let e,t,i,a,n=!1,o=!1,c=!1,u,l,d=!1;const h=0;return Ke(r,({tag:f,type:p,value:m,valueSize:T})=>{if(f===S.SeekID){const b=ye(m,p);l=kt(b)}else f!==S.SeekPosition&&(l=void 0);return f===S.Segment?(e=m.byteOffset,t=m.byteOffset+T):f===S.Info?n=!0:f===S.SeekHead?o=!0:f===S.TimestampScale?i=ye(m,p):f===S.Duration?a=ye(m,p):f===S.SeekPosition&&l===S.Cues?u=ye(m,p):f===S.Tracks?Ke(m,({tag:b,type:g,value:C})=>b===S.ProjectionType?(d=ye(C,g)===1,!1):!0):n&&o&&Vi.includes(f)&&(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:u,is3dVideo:d,stereoMode:h,projectionType:Et.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ya=r=>{if(s.isNullable(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},va=(r,e)=>{let t=!1,i=!1;const a=c=>s.isNonNullable(c.time)&&s.isNonNullable(c.position),n=[];let o;return Ke(r,({tag:c,type:u,value:l})=>{switch(c){case S.Cues:t=!0;break;case S.CuePoint:o&&a(o)&&n.push(o),o={};break;case S.CueTime:o&&(o.time=ye(l,u));break;case S.CueTrackPositions:break;case S.CueClusterPosition:o&&(o.position=ye(l,u));break;default:t&&Vi.includes(c)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((c,u)=>{const{time:l,position:d}=c,h=n[u+1];return{status:L.NONE,time:{from:l,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},Ta=r=>{let e=0,t=!1;try{Ke(r,i=>i.tag===S.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ba.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[S.SimpleBlock,S.BlockGroup,S.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Ea={validateData:Sa,parseInit:ga,getIndexRange:ya,parseSegments:va,parseFeedableSegmentChunk:Ta},ka=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)},ci=r=>{if(!r.startsWith("P"))return;const e=(o,c)=>{const u=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(u)?0:u)*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},ze=(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,u)=>s.isNullable(n)?c:s.isNullable(u)?n:n.padStart(parseInt(u,10),"0"))}return t},wa=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],c=n.querySelector("BaseURL")?.textContent?.trim()??"",u=o.children,l=n.getAttribute("type")==="dynamic",d=n.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let f;const p=n.getAttribute("mediaPresentationDuration"),m=o.getAttribute("duration"),b=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)f=ci(p);else if(m){const y=ci(m);s.isNonNullable(y)&&(f=y)}else b&&(f=parseInt(b,10));let g=0;const C=n.getAttribute("profiles")?.split(",")??[],P=C.includes(Tt.WEBM_AS_IN_FFMPEG)||C.includes(Tt.WEBM_AS_IN_SPEC)?Xe.WEBM:Xe.MP4;for(const y of u){const E=y.getAttribute("mimeType"),_=y.getAttribute("codecs"),V=y.getAttribute("contentType")??E?.split("/")[0],R=y.getAttribute("profiles")?.split(",")??[],M=y.querySelectorAll("Representation"),k=y.querySelector("SegmentTemplate");if(V===K.TEXT){for(const A of M){const N=A.getAttribute("id")||"",z=y.getAttribute("lang"),X=A.querySelector("BaseURL")?.textContent?.trim()??"",le=new URL(X||c,e).toString(),$=N.includes("_auto");a[K.TEXT].push({id:N,lang:z,isAuto:$,kind:K.TEXT,url:le})}continue}for(const A of M){const N=A.getAttribute("mimeType")??E,z=A.getAttribute("codecs")??_??"",X=A.getAttribute("contentType")??N?.split("/")[0]??V,le=y.getAttribute("profiles")?.split(",")??[],$=parseInt(A.getAttribute("width")??"",10),O=parseInt(A.getAttribute("height")??"",10),Q=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,W=A.getAttribute("frameRate")??"",te=A.getAttribute("quality")??void 0,Pe=W?ka(W):void 0,Lt=A.getAttribute("id")??(g++).toString(10),ft=X==="video"?`${O}p`:X==="audio"?`${Q}Kbps`:z,F=`${Lt}@${ft}`,ie=A.querySelector("BaseURL")?.textContent?.trim()??"",se=new URL(ie||c,e).toString(),ue=[...C,...R,...le];let Ee;const et=A.querySelector("SegmentBase"),ae=A.querySelector("SegmentTemplate")??k;if(et){const de=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[pe,xt]=de.split("-").map(Ye=>parseInt(Ye,10)),De={from:pe,to:xt},tt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[Rt,pt]=tt?tt.split("-").map(Ye=>parseInt(Ye,10)):[],it=tt?{from:Rt,to:pt}:void 0;Ee={type:oe.BYTE_RANGE,url:se,initRange:De,indexRange:it}}else if(ae){const de={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},pe=parseInt(ae.getAttribute("timescale")??"",10),xt=ae.getAttribute("initialization")??"",De=ae.getAttribute("media"),tt=parseInt(ae.getAttribute("startNumber")??"",10)??1,Rt=ze(xt,de);if(!De)throw new ReferenceError("No media attribute in SegmentTemplate");const pt=ae.querySelectorAll("SegmentTimeline S")??[],it=[];let Ye=0,Nt="",It=0;if(pt.length){let mt=tt,he=0;for(const Ge of pt){const me=parseInt(Ge.getAttribute("d")??"",10),Ne=parseInt(Ge.getAttribute("r")??"",10)||0,St=parseInt(Ge.getAttribute("t")??"",10);he=Number.isFinite(St)?St:he;const Vt=me/pe*1e3,ji=he/pe*1e3;for(let bt=0;bt<Ne+1;bt++){const Yi=ze(De,{...de,segmentNumber:mt.toString(10),segmentTime:(he+bt*me).toString(10)}),Xt=(ji??0)+bt*Vt,Gi=Xt+Vt;mt++,it.push({time:{from:Xt,to:Gi},url:Yi})}he+=(Ne+1)*me,Ye+=(Ne+1)*Vt}It=he/pe*1e3,Nt=ze(De,{...de,segmentNumber:mt.toString(10),segmentTime:he.toString(10)})}else if(s.isNonNullable(f)){const he=parseInt(ae.getAttribute("duration")??"",10)/pe*1e3,Ge=Math.ceil(f/he);let me=0;for(let Ne=1;Ne<Ge;Ne++){const St=ze(De,{...de,segmentNumber:Ne.toString(10),segmentTime:me.toString(10)});it.push({time:{from:me,to:me+he},url:St}),me+=he}It=me,Nt=ze(De,{...de,segmentNumber:Ge.toString(10),segmentTime:me.toString(10)})}const Hi={time:{from:It,to:1/0},url:Nt};Ee={type:oe.TEMPLATE,baseUrl:se,segmentTemplateUrl:De,initUrl:Rt,totalSegmentsDurationMs:Ye,segments:it,nextSegmentBeyondManifest:Hi,timescale:pe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!N)continue;const Ce={video:K.VIDEO,audio:K.AUDIO,text:K.TEXT}[X];Ce&&a[Ce].push({id:F,kind:Ce,segmentReference:Ee,profiles:ue,duration:f,bitrate:Q,mime:N,codecs:z,width:$,height:O,fps:Pe,quality:te})}}return{dynamic:l,liveAvailabilityStartTime:h,duration:f,container:P,representations:a}},Aa=({id:r,width:e,height:t,bitrate:i,fps:a,quality:n})=>{const o=(n?$t(n):void 0)??s.videoSizeToQuality({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a}},$a=({id:r,bitrate:e})=>({id:r,bitrate:e}),Pa=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},Ca=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),li=r=>"url"in r,qe=r=>r.type===oe.TEMPLATE,Ht=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);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=[];subscription=new s.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Je;destroyAbortController=new Je;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:c,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:d}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=l,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=c,this.isActiveLowLatency=u,this.isLive=!!d?.dynamic,this.container=i,i){case Xe.MP4:this.containerParser=ma;break;case Xe.WEBM:this.containerParser=Ea;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 Us(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,ni(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.isLive||(i.forEach(o=>o.status=L.NONE),this.pruneBuffer(n,1/0,!0)),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 Je,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(l=>e>=l.time.from&&e<l.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=Qe(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ni(this.sourceBuffer.buffered)>=this.bufferLimit){const l=Qe(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(i,t.segmentReference.type,n),c.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(c.includes(a))l="high";else{const d=c.at(0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(c,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===L.FED&&!c.length&&Qe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=i.at(-1);u&&u.status===L.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}searchGaps(e,t){this.gaps=[];let i=0;const a=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+a}),i=n.time.to;s.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[];let n=0,o=t.length-1;do a.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,this.isActiveLowLatency()?[a[0]]:a}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 u=e.find(h=>h.id===c);u&&this.representations.set(c,u);const l=this.representations.get(c);if(!l||!qe(l.segmentReference))return;const d=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,d)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);s.assertNonNullable(i);const a=this.segments.get(t);s.assertNonNullable(a,"No segments for starting representation");const n=this.initData.get(t);if(s.assertNonNullable(n,"No init buffer 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||!qe(t.segmentReference))return;const i=t.segmentReference.segments.map(c=>({...c,status:L.NONE,size:void 0})),a=this.segments.get(t.id)??[],n=a.at(-1)?.time.to??0,o=i?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,c)}else{const c=i.slice(o+1);this.segments.set(t.id,[...a,...c])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!qe(i))return;const a=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=ze(i.segmentTemplateUrl,{segmentTime:a}),o=this.segments.get(t.id)??[],c=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));c&&(c.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:L.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}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:h,time:{from:f,to:p}},m)=>{const T=f<=i&&p>=i,b=f>i||T||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&f<=i+g||p<=i+g;return(h===L.NONE||h===L.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!Ot(this.sourceBuffer.buffered,i))&&b&&C});if(a===-1)return[];if(t!==oe.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,c=0;const u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=l||c<=d);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,c+=f.time.to+1-f.time.from,f.status===L.NONE||f.status===L.PARTIALLY_EJECTED)u.push(f);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===oe.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=L.DOWNLOADING;const a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);const{range:n,url:o,signal:c,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&c&&(await s.abortable(c,async function*(){const d=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted&&this.abortActiveSegments([e]));try{const d=await this.fetcher.fetch(o,{range:n,signal:c,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,c),a.segment.status=L.DOWNLOADED,this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){if(!Ht(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=L.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:a,url:n,signal:o,onProgress:c}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await s.abortable(o,async function*(){const u=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:a,onProgress:c,signal:o,priority:i}),this.failedDownloads=0}catch(u){if(!Ht(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}}prepareByteRangeFetchSegmentParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:a,signal:n,onProgress:(u,l)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:l,signal:n,onSegmentAppendFailed:o,globalFrom:a?a.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const a=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},c=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:d,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});c.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:a,signal:n,onProgress:l,onProgressTasks:c}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&s.isNonNullable(i)&&(t=Qe(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})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:a,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const c of this.activeSegments){const{segment:u}=c;if(c.representationId===t){if(n.aborted){a();continue}if(c.loadedBytes=i,c.loadedBytes>c.feedingBytes){const l=new DataView(e.buffer,e.byteOffset+c.feedingBytes,c.loadedBytes-c.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(l);d?.byteLength&&(u.status=L.PARTIALLY_FED,c.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),c.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const c=this.representations.get(t);if(!c)return;const u=c.segmentReference.type,l=e.byteLength;for(const d of this.activeSegments){const{segment:h}=d,f=u===oe.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:l;if(d.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const T=f?h.byte.from-i:0,b=f?h.byte.to-i:e.byteLength,g=T<a,C=b<=a;if(h.status===L.DOWNLOADING&&g&&C){h.status=L.DOWNLOADED;const P=new DataView(e.buffer,e.byteOffset+T,p);this.sourceBufferTaskQueue.append(P,n).then(y=>y&&!n.aborted?this.onSegmentFullyAppended(d,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(d.loadedBytes=Math.min(p,a-T),d.loadedBytes>d.feedingBytes)){const P=new DataView(e.buffer,e.byteOffset+T+d.feedingBytes,d.loadedBytes-d.feedingBytes),y=d.loadedBytes===p?P:this.containerParser.parseFeedableSegmentChunk(P);y?.byteLength&&(h.status=L.PARTIALLY_FED,d.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,n).then(E=>{if(n.aborted)o();else if(E)d.fedBytes+=y.byteLength,d.fedBytes===p&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=L.FED,li(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const a of this.segments.get(i.id)??[])a.status===L.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=L.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===L.PARTIALLY_FED||e.status===L.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=L.NONE),e.status=L.PARTIALLY_EJECTED):e.status=L.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=ri(()=>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(u=>setTimeout(u,c))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async c=>{if(!c)return;const{init:u,dataView:l,segments:d}=c,h=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,h);let f=d;this.isLive&&qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).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 u=l=>{n=Math.min(n,l.time.from),o=Math.max(o,l.time.to);const d=li(l)?l.size??0:l.byte.to-l.byte.from;a+=d};for(const l of this.segments.values())for(const d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status===L.FED&&u(d)}if(c=isFinite(n)&&isFinite(o),!c){a=0,n=1/0,o=-1/0;for(const l of this.segments.values())for(const d of l){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status===L.FED&&u(d)}}if(c=isFinite(n)&&isFinite(o),!c)for(let l=0;l<this.sourceBuffer.buffered.length;l++){const d=this.sourceBuffer.buffered.start(l)*1e3,h=this.sourceBuffer.buffered.end(l)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===L.NONE&&Math.round(p.time.from)<=Math.round(d)&&Math.round(p.time.to)>=Math.round(h)){n=d,o=h;break}}if(c=isFinite(n)&&isFinite(o),!c&&i){a=0,n=1/0,o=-1/0;const l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const h of d)h.time.from>e+l&&h.status===L.FED&&u(h)}return c=isFinite(n)&&isFinite(o),c?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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=ri(()=>{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!==L.FED&&n!==L.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),c=Math.ceil(a.time.to),u=e.some(d=>d.from-t<=o&&d.to+t>=c),l=e.filter(d=>o>=d.from-t&&o<=d.to+t||c>=d.from-t&&c<=d.to+t);u||(l.length===1?a.status=L.PARTIALLY_EJECTED:a.status=L.NONE)}}}var jt=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Da=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}},We;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(We||(We={}));class La{throughputEstimator;requestQuic;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);abortAllController=new Je;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}=Da(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=s.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=jt(t));const i=yield ut(t,{signal:this.abortAllController.signal}).catch(st);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=s.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?We.HEADER:We.PARAM,range:i,onProgress:a,priority:n="auto",signal:o,measureThroughput:c=!0,isLowLatency:u=!1}={}){let l=e;const d=new Headers;if(i)switch(t){case We.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case We.PARAM:{const R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:s.assertNever(t)}this.requestQuic&&(l=jt(l));let h=this.abortAllController.signal,f;if(o){const R=new Je;if(f=s.merge(s.fromEvent(this.abortAllController.signal,"abort"),s.fromEvent(o,"abort")).subscribe(()=>{try{R.abort()}catch(M){st(M)}}),this.abortAllController.signal.aborted||o.aborted)try{R.abort()}catch(M){st(M)}h=R.signal}const p=s.now(),m=yield ut(l,{priority:n,headers:d,signal:h}).catch(st),T=s.now();if(!m)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(T-p),!m.ok||!m.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!c)return f?.unsubscribe(),m.arrayBuffer();const[b,g]=m.body.tee(),C=b.getReader();c&&this.throughputEstimator?.trackStream(g,u);let P=0,y=new Uint8Array(0),E=!1;const _=R=>{f?.unsubscribe(),E=!0,st(R)},V=s.abortable(h,async function*({done:R,value:M}){if(P===0&&this.lastRequestFirstBytes$.next(s.now()-p),h.aborted){f?.unsubscribe();return}if(!R&&M){const k=new Uint8Array(y.length+M.length);k.set(y),k.set(M,y.length),y=k,P+=M.byteLength,a?.(new DataView(y.buffer),P),yield C?.read().then(V,_)}}.bind(this));return yield C?.read().then(V,_),f?.unsubscribe(),E?null:y.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:a}=e;switch(a){case oe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case oe.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!==oe.BYTE_RANGE)return null;const{from:a,to:n}=e.initRange;let o=a,c=n,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=n+1===l,u&&(o=Math.min(l,a),c=Math.max(d,n))),o=Math.min(o,0);const h=yield this.fetch(e.url,{range:{from:o,to:c},priority:i,measureThroughput:!1});if(!h)return null;const f=new DataView(h,a-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let T;if(u)T=new DataView(h,m.from-o,m.to-m.from+1);else{const g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;T=new DataView(g)}const b=t.parseSegments(T,p,m);return{init:p,dataView:new DataView(h),segments:b}}.bind(this));fetchTemplateRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==oe.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:L.NONE,size:void 0})),dataView:new DataView(a)}:null}.bind(this))}const st=r=>{if(!Ht(r))throw r},Yt=1e3,wt=(r,e,t)=>t*e+(1-t)*r,Bi=(r,e)=>r.reduce((t,i)=>t+i,0)/e,xa=(r,e,t,i)=>{let a=0,n=t;const o=Bi(r,e),c=e<i?e:i;for(let u=0;u<c;u++)r[n]>o?a++:a--,n=(r.length+n-1)%r.length;return Math.abs(a)===c};class Wt{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 Ra extends Wt{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=wt(this.slow,e,this.params.emaAlphaSlow),this.fast=wt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Na extends Wt{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Bi(this.pastMeasures,this.takenMeasures);this.emaSmoothed=wt(this.emaSmoothed,e,this.params.emaAlpha);const i=xa(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Ia extends Wt{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?wt(this.smoothed,e,this.params.emaAlpha):e}}class Gt{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ra({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Na({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ia({initial:e,label:"liveEdgeDelay",...t})}}const Va=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)},Ie=()=>window.ManagedMediaSource||window.MediaSource,Mi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Ba=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Ma=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,di=["timeupdate","progress","play","seeked","stalled","waiting"];var ne;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(ne||(ne={}));let _a=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new s.Subscription;representationSubscription=new s.Subscription;fetcher;state$=new q(ne.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);livePositionFromPlayer$=new s.ValueSubject(0);liveEstimatedDelay;waitingEventInterval;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new s.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Je;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new La({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=s.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=fe(t,i,J.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ne.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(ne.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 null;let t;try{t=wa(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)&&Ie()?.isTypeSupported?.(`${n}; codecs="${o}"`)||a===K.TEXT);return t.dynamic&&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);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=fe(this.manifestUrlString,t,J.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(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,i){s.assertNonNullable(this.manifest),s.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ne.REPRESENTATIOS_READY);const a=p=>{this.representationSubscription.add(s.fromEvent(p,"error").pipe(s.filter(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ma():new MediaSource;const n=document.createElement("source");if(a(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),this.tuning.useManagedMediaSource&&Mi())if(i){const p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const o={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new ui(K.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,o),this.bufferManagers=[this.videoBufferManager],s.isNonNullable(t)&&(this.audioBufferManager=new ui(K.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,o),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(p=>{if(this.element?.paused){const m=Zt(this.manifestUrlString,J.DASH_CMAF_OFFSET_P);this.manifestUrlString=fe(this.manifestUrlString,m+Yt,J.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(s.merge(...di.map(p=>s.fromEvent(this.element,p))).pipe(s.map(p=>this.element?Qe(this.element.buffered,this.element.currentTime*1e3):0),s.filterChanged(),s.filter(p=>!!p),s.tap(p=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(s.filter(m=>this.isActiveLowLatency&&!!m)).subscribe(m=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(m=>{if(!this.isActiveLowLatency)return;const T=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,C=m-T;let P=1+Math.sign(C)*g;Math.abs(C)<b?P=1:Math.abs(C)>b*2&&(P=1+Math.sign(C)*g*2),Va(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let T=0;if(m){const b=(this.element?.currentTime??0)*1e3;T=Math.min(...this.bufferManagers.map(C=>C.getLiveSegmentsToLoadState(this.manifest)?.to??0))-b}T&&this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let p=0;this.representationSubscription.add(s.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:m,bufferLength:T})=>{if(s.assertNonNullable(this.element),this.isUpdatingLive)return;const b=this.element.playbackRate,g=Zt(this.manifestUrlString,J.DASH_CMAF_OFFSET_P),C=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(C,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,_=this.isActiveLowLatency?T:m;let V=be.None;if(this.isActiveLowLatency?V=be.ActiveLowLatency:_<P+E&&_>=P?V=be.LiveWithTargetOffset:g!==0&&_<P&&(V=be.LiveForwardBuffering),isFinite(m)&&(p=m>p?m:p),V===be.LiveForwardBuffering||V===be.LiveWithTargetOffset){const R=p-(P+y),M=this.normolizeLiveOffset(Math.trunc(g+R/b)),k=Math.abs(M-g);let A;!m||k<=this.tuning.dashCmafLive.offsetCalculationError?A=g:M>0&&k>this.tuning.dashCmafLive.offsetCalculationError?A=M:A=0,this.manifestUrlString=fe(this.manifestUrlString,A,J.DASH_CMAF_OFFSET_P)}V!==be.None&&V!==be.ActiveLowLatency&&(p=0,this.updateLive())}))}const c=s.merge(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(s.map(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),u=s.merge(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(s.map(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(s.merge(this.forceEnded$,s.combine({allBuffersFull:c,someBufferEnded:u}).pipe(s.filter(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(s.merge(...this.bufferManagers.map(p=>p.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(p=>this.source?.addEventListener("sourceopen",p)));const l=this.manifest.duration??0,d=(p,m)=>Math.max(p,m.duration??0),h=this.manifest.representations.audio.reduce(d,l),f=this.manifest.representations.video.reduce(d,l);(h||f)&&(this.source.duration=Math.max(h,f)/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(ne.REPRESENTATIOS_READY)}.bind(this));initBuffer(){s.assertNonNullable(this.element),this.state$.setState(ne.RUNNING),this.subscription.add(s.merge(...di.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&&Ot(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){return{[K.VIDEO]:this.videoBufferManager,[K.AUDIO]:this.audioBufferManager,[K.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),Ot(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?.querySelectorAll("source").forEach(e=>e.remove()),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(ne.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(),window.clearInterval(this.waitingEventInterval),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:s.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,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):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(a)&&(this.element.currentTime=a/1e3)}}};class Fa{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Oa{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 Ua=`#define GLSLIFY 1
38
38
  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;}`,Ha=`#ifdef GL_ES
39
39
  precision highp float;precision highp int;
40
40
  #else
@@ -42,5 +42,5 @@ precision highp float;
42
42
  #define GLSLIFY 1
43
43
  #endif
44
44
  #define PI 3.14159265358979323846264
45
- 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 ja{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 Fa(this.params.fov,this.params.orientation),this.cameraRotationManager=new Oa(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(Ua,this.gl.VERTEX_SHADER),i=this.createShader(Ha,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,u=t-a,l=e+i,d=t+a,h=e-i,f=t+a;return[n,o,c,u,l,d,h,f]}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}}const Ya=(r,e)=>new s.Observable(t=>{if(!window.IntersectionObserver)return;const i=()=>!!window.documentPictureInPicture.window||!!document.pictureInPictureElement,a={root:null},n=new IntersectionObserver((c,u)=>{c.forEach(l=>t.next(l.isIntersecting||i()))},{...a,...e});n.observe(r);const o=s.fromEvent(document,"visibilitychange").pipe(s.map(c=>!document.hidden||i())).subscribe(c=>t.next(c));return()=>{n.unobserve(r),o.unsubscribe}});class _i{scene3D;subscription=new s.Subscription;videoState=new q(Y.STOPPED);video;player;params;elementSize$=new s.ValueSubject(void 0);elementVisible$=new s.ValueSubject(!0);textTracksManager=new xe;droppedFramesManager=new Pi;videoTracks$=new s.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ys;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Fe(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(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new _a({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=He(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,u)=>this.subscription.add(c.subscribe(u,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(l=>l.map(({track:d})=>d)))}),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(ht(this.video,t.isLooped,a)),this.subscription.add(Ue(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ze(this.video,t.playbackRate,i.playbackRateState$,a)),n(Ms(this.video),this.elementSize$),n(Ya(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l===ne.MANIFEST_READY){const d=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();s.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((b,y)=>y.bitrate-b.bitrate),p=Array.from(h.video).sort((b,y)=>y.bitrate-b.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const y=$a(b);y&&this.audioTracks.push({track:y,representation:b})}for(const b of p){const y=Aa(b);if(y){d.push({track:y,representation:b});const C=!this.params.tuning.isAudioDisabled&&Pa(f,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(d);for(const b of m){const y=Ca(b);y&&this.textTracks.push({track:y,representation:b})}this.params.output.availableVideoTracks$.next(d.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const T=this.selectVideoRepresentation();s.assertNonNullable(T),this.player.initRepresentations(T.id,this.audioRepresentations.get(T.id)?.id,this.params.sourceHls)}else l===ne.REPRESENTATIOS_READY&&(this.videoState.setState(Y.READY),this.player.initBuffer())},a));const o=l=>e.error$.next({id:"RepresentationSwitch",category:s.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});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.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).subscribe(()=>{const l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!==ne.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);const p=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(h){let T=h.id;!this.elementVisible$.getValue()&&p&&(T=this.videoTracks$.getValue().map(y=>y.representation).sort((y,C)=>C.bitrate-y.bitrate).filter(y=>{const{width:C,height:P}=y,{width:g,height:E}=h,B=Math.min(C,P)+"p",I=Math.min(g,E)+"p";return s.isLowerOrEqual(B,I)&&s.isLowerOrEqual(B,m)}).map(y=>y.id)[0]),this.player.switchRepresentation(K.VIDEO,T).catch(o);const b=this.audioRepresentations.get(h.id);b&&this.player.switchRepresentation(K.AUDIO,b.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(s.filterChanged(),s.map(l=>l&&this.videoTracks$.getValue().find(({representation:{id:d}})=>d===l)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}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:l})=>l===exports.PlaybackState.READY),s.filterChanged());this.subscription.add(s.merge(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(s.merge(c,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const u=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:h}})=>h===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),n=Qe(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),u=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),l=Pt(this.videoTracks$.getValue().map(({track:h})=>h),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:c,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),d=e?l??i:i??l;return d&&this.videoTracks$.getValue().find(({track:h})=>h===d)?.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===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Y.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-o,a.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();return;case Y.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Y.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ja(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(){je(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Y.PAUSED),w(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),Oe(this.video)}}class Ga extends _i{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 qa extends _i{constructor(e){super(e),this.liveOffset=new zt}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(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.combine({interval:s.interval(Yt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()===Y.PLAYING&&!this.player.isActiveLowLatency){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===Y.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 Se={};var M;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(M||(M={}));const at=(r,e)=>new s.Observable(t=>{const i=(a,n)=>t.next(n);return r.on(e,i),()=>r.off(e,i)});class za{subscription=new s.Subscription;videoState=new q(M.INITIALIZING);video;params;hls;textTracksManager=new xe;trackLevels=new Map;constructor(e){this.video=Fe(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(Te(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),Oe(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||(Se.Hls=a.default,Se.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(Se.Hls,"hls.js not loaded"),this.hls=new Se.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){s.assertNonNullable(Se.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:s.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=He(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,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(ht(this.video,e.isLooped,i)),this.subscription.add(Ue(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(at(this.hls,Se.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:s.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),w(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},i)),n(at(this.hls,Se.Events.MANIFEST_PARSED).pipe(s.map(({levels:l})=>l.reduce((d,h)=>{const f=h.name||h.height.toString(10),{width:p,height:m}=h,T=$t(h.attrs.QUALITY??"")??s.videoSizeToQuality({width:p,height:m});if(!T)return d;const b=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,y={id:f.toString(),quality:T,bitrate:h.bitrate/1e3,size:{width:p,height:m},fps:b};return this.trackLevels.set(f,{track:y,level:h}),d.push(y),d},[]))),t.availableVideoTracks$),n(at(this.hls,Se.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){const d=[];for(const h of l.subtitleTracks){const f=h.name,p=h.attrs.URI||"",m=h.lang,T="internal";d.push({id:f,url:p,language:m,type:T})}e.internalTextTracks.startTransitionTo(d)}}),n(at(this.hls,Se.Events.LEVEL_LOADING).pipe(s.map(({url:l})=>Te(l))),t.hostname$),this.subscription.add(ke(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));const o=l=>Array.from(this.trackLevels.values()).find(({level:d})=>d===l)?.track,c=at(this.hls,Se.Events.LEVEL_SWITCHED).pipe(s.map(({level:l})=>o(this.hls.levels[l])));c.pipe(s.filter(s.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ke(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),l=>{if(s.isNullable(l))return;const d=this.trackLevels.get(l.id)?.level;if(!d)return;const h=this.hls.levels.indexOf(d),f=this.hls.currentLevel,p=this.hls.levels[f];!p||d.bitrate>p.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:c,onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=s.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(u.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!==M.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===V.Requested&&this.seek(a.position),t){case exports.PlaybackState.STOPPED:switch(e){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:s.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:s.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:s.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:s.assertNever(e)}break;default:s.assertNever(t)}};prepare(){this.videoState.startTransitionTo(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await je(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(M.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.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(M.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const hi="X-Playback-Duration";var fi=async r=>{const e=await ut(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 Qa=r=>{let e=null;if(r.QUALITY&&(e=$t(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},Wa=(r,e)=>{const t=r.split(`
46
- `),i=[],a=[];for(let n=0;n<t.length;n++){const o=t[n],c=o.match(/^#EXT-X-STREAM-INF:(.+)/),u=o.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!u)){if(c){const l=Object.fromEntries(c[1].split(",").map(b=>b.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,h=Qa(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const p=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let m;if(l.RESOLUTION){const[b,y]=l.RESOLUTION.split("x").map(C=>parseInt(C,10));b&&y&&(m={width:b,height:y})}const T=new URL(t[++n],e).toString();h&&i.push({id:d,quality:h,url:T,bandwidth:f,size:m,fps:p})}if(u){const l=Object.fromEntries(u[1].split(",").map(p=>p.split("=")).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,f=l.NAME;d&&h&&a.push({type:"internal",id:h,label:f,language:h,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Ja=r=>new Promise(e=>{setTimeout(()=>{e()},r)});let Bt=0;const Jt=async(r,e=r,t)=>{const a=await(await ut(r)).text();Bt+=1;try{const{qualityManifests:n,textTracks:o}=Wa(a,e);return{qualityManifests:n,textTracks:o}}catch{if(Bt<=t.manifestRetryMaxCount)return await Ja(s.getExponentialDelay(Bt-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Jt(r,e,t)}return{qualityManifests:[],textTracks:[]}};var U;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(U||(U={}));class Xa{subscription=new s.Subscription;videoState=new q(U.STOPPED);video;params;textTracksManager=new xe;masterManifest;manifests$=new s.ValueSubject([]);maxSeekBackTime$;liveOffset=new zt;manifestStartTime$=new s.ValueSubject(void 0);constructor(e){this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url},Jt(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:s.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(Te(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?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo(this.masterManifest),o.find(u=>u.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=He(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,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(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY),this.videoState.getState()===U.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(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&s.isNonNullable(l.to)){const h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===U.CHANGING_MANIFEST&&this.videoState.setState(u.to),c&&c.state===V.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:u})=>this.params.output.liveTime$.next(c+u*1e3),i)),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:u,quality:l,size:d,bandwidth:h,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.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),Oe(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:c,min:u}=t?.to??i??{};for(const[l,d]of[[c,"mq"],[u,"lq"]]){const h=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,h)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?J.DASH_CMAF_OFFSET_P:J.OFFSET_P,o=fe(a.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),fi(o).then(c=>{if(!s.isNullable(c))this.maxSeekBackTime$.next(c);else{const u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(s.isNullable(u)||!isFinite(u))try{ut(o).then(l=>l.text()).then(l=>{const d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){const h=new URL(d,o).toString();fi(h).then(f=>{s.isNullable(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),w(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(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(U.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(t===U.STOPPED){this.videoState.startTransitionTo(U.READY),this.prepare();return}if(n||o||c){const d=this.videoState.getState();this.videoState.setState(U.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),l.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!==exports.PlaybackState.PAUSED&&l.state===V.Requested){this.videoState.startTransitionTo(U.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case U.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed());return;case U.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(U.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to===exports.PlaybackState.PAUSED&&(w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case U.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var j;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(j||(j={}));class Ka{subscription=new s.Subscription;videoState=new q(j.STOPPED);video;params;textTracksManager=new xe;masterManifest;manifests$=new s.ValueSubject([]);constructor(e){this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video),this.masterManifest={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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Jt(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),n=a?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo(this.masterManifest),o.find(u=>u.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=He(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u));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(ht(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===j.READY&&this.videoState.setState(j.READY),this.videoState.getState()===j.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&s.isNonNullable(l.to)){const h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const f=this.manifests$.getValue().find(p=>p.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url));const p=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(p!==m){const T=this.params.output.element$.getValue();T&&(this.params.desiredState.playbackRate.setState(p),T.playbackRate=p)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===j.CHANGING_MANIFEST&&this.videoState.setState(u.to),c.state===V.Requested&&this.seek(c.position)},i))),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:u,quality:l,size:d,bandwidth:h,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!s.isIOS()||!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 u=0;u<c.length;u++)c[u].mode="hidden"},i))}const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.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),Oe(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:n,min:o}=t?.to??i??{};for(const[c,u]of[[n,"mq"],[o,"lq"]]){const l=String(parseFloat(c||""));u&&c&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(j.PAUSED),w(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(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==j.STOPPED&&(this.videoState.startTransitionTo(j.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(j.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(t===j.STOPPED){this.videoState.startTransitionTo(j.READY),this.prepare();return}if(n||o||c){const d=this.videoState.getState();this.videoState.setState(j.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:h}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),l.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:h*1e3,forcePrecise:!0});return}switch(a?.to!==exports.PlaybackState.PAUSED&&l.state===V.Requested&&this.seek(l.position),t){case j.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(j.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed());return;case j.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(j.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case j.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case j.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var G;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(G||(G={}));class Za{subscription=new s.Subscription;videoState=new q(G.STOPPED);video;trackUrls={};params;textTracksManager=new xe;constructor(e){this.params=e,this.video=Fe(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=He(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,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(ht(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY);const c=this.params.desiredState.videoTrack.getTransition();if(c&&s.isNonNullable(c.to)){this.params.desiredState.videoTrack.setState(c.to),this.params.output.currentVideoTrack$.next(this.trackUrls[c.to.id].track);const u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){const d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()===G.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),Oe(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;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=jt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),w(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!==G.STOPPED&&(this.videoState.startTransitionTo(G.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(G.STOPPED),w(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!==G.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(o){const{currentTime:u}=this.video;this.prepare(),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:u*1e3,forcePrecise:!0}),o.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[o.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested&&this.seek(c.position),e){case G.READY:t===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const a=Object.values(this.trackUrls).find(c=>!s.isInvariantQuality(c.track.quality)&&s.isLowerOrEqual(c.track.quality,e))?.track,n=this.params.desiredState.videoTrack.getState()?.id,o=this.trackUrls[n??"0"]?.track;if(a&&o&&s.isHigherOrEqual(o.quality,a.quality)&&(t=a),!t){const c=Object.values(this.trackUrls).filter(l=>!s.isInvariantQuality(l.track.quality)&&s.isHigher(l.track.quality,e)),u=c.length;u&&(t=c[u-1].track)}t&&(i=t.quality)}else if(!e){const a=Object.values(this.trackUrls).map(n=>n.track);t=Pt(a,{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)),this.params.output.autoVideoTrackLimits$.next({max:i})}}const pi=["stun:videostun.mycdn.me:80"],er=1e3,tr=3,_t=()=>null;class ir{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=_t;externalStopCallback=_t;externalErrorCallback=_t;constructor(e,t){this.options=this.normalizeOptions(t);const 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:pi}]};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),er)}normalizeOptions(e={}){const t={stunServerList:pi,maxRetryNumber:tr,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var H;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(H||(H={}));class sr{subscription;params;log;video;videoState=new q(H.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=Fe(e.container),this.liveStreamClient=new ir(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),Oe(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=He(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===H.READY&&this.videoState.setState(H.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ue(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case H.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case H.READY:break;case H.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case H.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return 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(Te(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,w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(H.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:s.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),w(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!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(H.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case H.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(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 Fi=s.getCurrentBrowser().device===s.CurrentClientDevice.Android,At=document.createElement("video"),ar='video/mp4; codecs="avc1.42000a,mp4a.40.2"',rr='video/mp4; codecs="hev1.1.6.L93.B0"',Oi='video/webm; codecs="vp09.00.10.08"',Ui='video/webm; codecs="av01.0.00M.08"',nr='audio/mp4; codecs="mp4a.40.2"',or='audio/webm; codecs="opus"',Ve={mms:Bi(),mse:Ma(),hls:!!(At.canPlayType?.("application/x-mpegurl")||At.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},re={mp4:!!At.canPlayType?.("video/mp4"),webm:!!At.canPlayType?.("video/webm"),cmaf:!0},ve={h264:!!Ie()?.isTypeSupported?.(ar),h265:!!Ie()?.isTypeSupported?.(rr),vp9:!!Ie()?.isTypeSupported?.(Oi),av1:!!Ie()?.isTypeSupported?.(Ui),aac:!!Ie()?.isTypeSupported?.(nr),opus:!!Ie()?.isTypeSupported?.(or)},rt=(ve.h264||ve.h265)&&ve.aac;var Le;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Le||(Le={}));var Ae;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(Ae||(Ae={}));let Me;const cr=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:Ui}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Oi}})]);Me={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{cr()}catch(r){console.error(r)}const dt=Ve.hls&&re.mp4,lr=()=>Object.keys(ve).filter(r=>ve[r]),ur=(r,e=!1,t=!1)=>{const i=Ve.mse||Ve.mms&&t;return r.filter(a=>{switch(a){case exports.VideoFormat.DASH_SEP:return i&&re.mp4&&rt;case exports.VideoFormat.DASH_WEBM:return i&&re.webm&&ve.vp9&&ve.opus;case exports.VideoFormat.DASH_WEBM_AV1:return i&&re.webm&&ve.av1&&ve.opus;case exports.VideoFormat.DASH_LIVE:return Ve.mse&&re.mp4&&rt;case exports.VideoFormat.DASH_LIVE_CMAF:return i&&re.mp4&&rt&&re.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return i&&re.mp4&&rt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return dt||e&&Ve.mse&&re.mp4&&rt;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return dt;case exports.VideoFormat.MPEG:return re.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ve.webrtc&&Ve.ws&&ve.h264&&(re.mp4||re.webm);default:return s.assertNever(a)}})},nt=r=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(r){case Le.VP9:return[e,t];case Le.AV1:return[t,e];case Le.NONE:return[];case Le.SMOOTH:return Me?Me[t].smooth?[t,e]:Me[e].smooth?[e,t]:[t,e]:[e,t];case Le.POWER_EFFICIENT:return Me?Me[t].powerEfficient?[t,e]:Me[e].powerEfficient?[e,t]:[t,e]:[e,t];default:s.assertNever(r)}return[e,t]},dr=({webmCodec:r,androidPreferredFormat:e})=>{if(Fi)switch(e){case Ae.MPEG:return[exports.VideoFormat.MPEG,...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case Ae.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case Ae.DASH:return[...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return dt?[...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},hr=({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(Fi)switch(r){case Ae.DASH:{c=n;break}case Ae.HLS:case Ae.MPEG:{c=o;break}}else dt?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 fr=r=>new s.Observable(e=>{const t=new s.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(s.map(({from:l,to:d})=>`${l}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$.pipe(s.map(({type:l})=>l!==void 0)),o=new s.Subject;let c=0,u="unknown";return t.add(i.subscribe(l=>{c&&window.clearTimeout(c),u=l,c=window.setTimeout(()=>o.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(c),u="unknown",c=0})),t.add(n.subscribe(l=>{c&&(window.clearTimeout(c),c=0,l&&(c=window.setTimeout(()=>o.next(u),r.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const pr={chunkDuration:5e3,maxParallelRequests:5};class mr{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=ur([...hr(this.params.tuning),...dr(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).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!==V.None;if(this.params.desiredState.seekState.setState({state:V.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 Z.SCREEN:return this.createScreenProvider(t);case Z.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_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const c=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[exports.VideoFormat.HLS_ONDEMAND]||t[exports.VideoFormat.HLS]);return s.assertNonNullable(c),new Ga({...o,source:c,sourceHls:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new qa({...o,source:c})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),dt||!this.params.tuning.useHlsJs?new Ka({...o,source:c}):new za({...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 Xa({...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 Za({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Is({...o,source:c,config:{...pr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new sr({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 ns({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()?Z.CHROMECAST:Z.SCREEN}chooseFormat(e){switch(e){case Z.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Z.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return s.assertNever(e)}}skipFormat(e){switch(e){case Z.SCREEN:return this.screenFormatsIterator.next();case Z.CHROMECAST:return this.chromecastFormatsIterator.next();default:return s.assertNever(e)}}handleNoFormatsError(e){switch(e){case Z.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Z.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$,fr({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===Z.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Z.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),u=i<this.params.tuning.providerErrorLimit;c&&(o&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(n??Z.SCREEN)}})),e}}const Sr=5e3,bi="one_video_throughput",gi="one_video_rtt",ct=window.navigator.connection,yi=()=>{const r=ct?.downlink;if(s.isNonNullable(r)&&r!==10)return r*1e3},vi=()=>{const r=ct?.rtt;if(s.isNonNullable(r)&&r!==3e3)return r},Ti=(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(bi)||(e.useBrowserEstimation?yi():void 0)||Sr,i=lt.load(gi)??(e.useBrowserEstimation?vi():void 0)??0;if(this.throughput$=new s.ValueSubject(t),this.rtt$=new s.ValueSubject(i),this.rttAdjustedThroughput$=new s.ValueSubject(Ti(t,i,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(i,1,e),e.useBrowserEstimation){const a=()=>{const o=yi();o&&this.throughput.next(o);const c=vi();s.isNonNullable(c)&&this.rtt.next(c)};ct&&"onchange"in ct&&this.subscription.add(s.fromEvent(ct,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{s.safeStorage.set(bi,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{s.safeStorage.set(gi,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})=>Ti(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(),u=o-t,l=c-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,n=s.now(),o=0,c=s.now();const u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:h})=>{if(d)!t&&this.addRawSpeed(a,s.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(s.now()-c<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=h.byteLength;else{const p=c-n;p&&this.addRawSpeed(o,p,1,t),o=h.byteLength,n=s.now()}c=s.now()}else a+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&s.now()-c>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,s.now()-c,this.concurrentDownloads.size),o=0,c=s.now());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(lt.sanityCheck(e,t,a)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=s.safeStorage.get(e);if(s.isNonNullable(t))return parseInt(t,10)??void 0}}const Ei={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,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:s.VideoQuality.Q_480P,activeVideoAreaThreshold:.1},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,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},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:Le.VP9,androidPreferredFormat:Ae.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},br=r=>({...s.fillWithDefault(r,Ei),configName:[...r.configName??[],...Ei.configName]});var ki=({seekState:r,position$:e})=>s.merge(r.stateChangeEnded$.pipe(s.map(({to:t})=>t.state===V.None?void 0:(t.position??NaN)/1e3),s.filter(s.isNonNullable)),e.pipe(s.filter(()=>r.getState().state===V.None))),gr=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return s.assertNonNullable(e,`Wrong container or containerId {${r.container}}`),e};const yr=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(s.filter(a=>a.length>0),s.once()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};class vr{subscription=new s.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new s.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new q(exports.PlaybackState.STOPPED),seekState:new q({state:V.None}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({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:Ss};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=br(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new es({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 u=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:s.ErrorCategory.WTF,message:d,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.domContainer=gr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new mr({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:V.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();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(s.filter(i=>i.length>0),s.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),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 yr(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===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(){if(!this.providerContainer)return 0;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===V.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===V.Requested?this.desiredState.seekState.setState({...o,state:V.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===V.Applying&&(this.desiredState.seekState.setState({state:V.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,u)=>s.isInvariantQuality(c)?1:s.isInvariantQuality(u)?-1:s.isHigher(u,c)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const c={};for(const u of o)u.fps&&(c[u.quality]=u.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:ki({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(s.map(({isLive:o,position:c,isLowLatency:u})=>{const l=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(c)<l/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:u})=>o&&(Math.abs(u)-Math.abs(c))*1e3<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(ki({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(),u=e.providerOutput.element$.getValue(),l=this.chromecastInitializer.castState$.getValue();let d;l===exports.ChromecastState.CONNECTED?d=exports.Surface.SECOND_SCREEN:u?o?d=exports.Surface.PIP:c?d=exports.Surface.FULLSCREEN:d=exports.Surface.INLINE:d=exports.Surface.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}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;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Pt(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),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),ms(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ps(t)),this.providerContainer.current$.subscribe(({type:t})=>gt("provider",t)),e.duration$.subscribe(t=>gt("duration",t)),e.availableVideoTracks$.pipe(s.filter(t=>!!t.length),s.once()).subscribe(t=>gt("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)),gt("codecs",lr())}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))}setVideoTrackIdByQuality(e,t){const i=e.find(a=>a.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const Tr=`@vkontakte/videoplayer-core@${wi}`;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=vr;exports.SDK_VERSION=Tr;exports.VERSION=wi;
45
+ 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 ja{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 Fa(this.params.fov,this.params.orientation),this.cameraRotationManager=new Oa(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(Ua,this.gl.VERTEX_SHADER),i=this.createShader(Ha,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,u=t-a,l=e+i,d=t+a,h=e-i,f=t+a;return[n,o,c,u,l,d,h,f]}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}}const Ya=(r,e)=>new s.Observable(t=>{if(!window.IntersectionObserver)return;const i=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,a={root:null},n=new IntersectionObserver((c,u)=>{c.forEach(l=>t.next(l.isIntersecting||i()))},{...a,...e});n.observe(r);const o=s.fromEvent(document,"visibilitychange").pipe(s.map(c=>!document.hidden||i())).subscribe(c=>t.next(c));return()=>{n.unobserve(r),o.unsubscribe}});class _i{scene3D;subscription=new s.Subscription;videoState=new q(Y.STOPPED);video;player;params;elementSize$=new s.ValueSubject(void 0);elementVisible$=new s.ValueSubject(!0);textTracksManager=new xe;droppedFramesManager=new Pi;videoTracks$=new s.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ys;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Fe(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(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new _a({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=He(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,u)=>this.subscription.add(c.subscribe(u,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(l=>l.map(({track:d})=>d)))}),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(ht(this.video,t.isLooped,a)),this.subscription.add(Ue(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ze(this.video,t.playbackRate,i.playbackRateState$,a)),n(Bs(this.video),this.elementSize$),n(Ya(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l===ne.MANIFEST_READY){const d=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();s.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((b,g)=>g.bitrate-b.bitrate),p=Array.from(h.video).sort((b,g)=>g.bitrate-b.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const g=$a(b);g&&this.audioTracks.push({track:g,representation:b})}for(const b of p){const g=Aa(b);if(g){d.push({track:g,representation:b});const C=!this.params.tuning.isAudioDisabled&&Pa(f,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(d);for(const b of m){const g=Ca(b);g&&this.textTracks.push({track:g,representation:b})}this.params.output.availableVideoTracks$.next(d.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const T=this.selectVideoRepresentation();s.assertNonNullable(T),this.player.initRepresentations(T.id,this.audioRepresentations.get(T.id)?.id,this.params.sourceHls)}else l===ne.REPRESENTATIOS_READY&&(this.videoState.setState(Y.READY),this.player.initBuffer())},a));const o=l=>e.error$.next({id:"RepresentationSwitch",category:s.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});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.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).subscribe(()=>{const l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!==ne.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);const p=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(h){let T=h.id;!this.elementVisible$.getValue()&&p&&(T=this.videoTracks$.getValue().map(g=>g.representation).sort((g,C)=>C.bitrate-g.bitrate).filter(g=>{const C=s.videoSizeToQuality(g),P=s.videoSizeToQuality(h);if(C&&P)return s.isLowerOrEqual(C,P)&&s.isLowerOrEqual(C,m)}).map(g=>g.id)[0]),this.player.switchRepresentation(K.VIDEO,T).catch(o);const b=this.audioRepresentations.get(h.id);b&&this.player.switchRepresentation(K.AUDIO,b.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(s.filterChanged(),s.map(l=>l&&this.videoTracks$.getValue().find(({representation:{id:d}})=>d===l)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}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:l})=>l===exports.PlaybackState.READY),s.filterChanged());this.subscription.add(s.merge(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(s.merge(c,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const u=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:h}})=>h===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),n=Qe(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),u=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),l=Pt(this.videoTracks$.getValue().map(({track:h})=>h),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:c,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),d=e?l??i:i??l;return d&&this.videoTracks$.getValue().find(({track:h})=>h===d)?.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===I.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Y.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-o,a.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();return;case Y.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Y.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ja(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(){je(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Y.PAUSED),w(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),Oe(this.video)}}class Ga extends _i{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 qa extends _i{constructor(e){super(e),this.liveOffset=new zt}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(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.combine({interval:s.interval(Yt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()===Y.PLAYING&&!this.player.isActiveLowLatency){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===Y.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 Se={};var B;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(B||(B={}));const at=(r,e)=>new s.Observable(t=>{const i=(a,n)=>t.next(n);return r.on(e,i),()=>r.off(e,i)});class za{subscription=new s.Subscription;videoState=new q(B.INITIALIZING);video;params;hls;textTracksManager=new xe;trackLevels=new Map;constructor(e){this.video=Fe(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(Te(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),Oe(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||(Se.Hls=a.default,Se.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(Se.Hls,"hls.js not loaded"),this.hls=new Se.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(B.STOPPED)}subscribe(){s.assertNonNullable(Se.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:s.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=He(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,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(ht(this.video,e.isLooped,i)),this.subscription.add(Ue(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(at(this.hls,Se.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:s.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),w(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===B.READY&&this.videoState.setState(B.READY),this.videoState.getState()===B.PLAYING&&this.playIfAllowed()},i)),n(at(this.hls,Se.Events.MANIFEST_PARSED).pipe(s.map(({levels:l})=>l.reduce((d,h)=>{const f=h.name||h.height.toString(10),{width:p,height:m}=h,T=$t(h.attrs.QUALITY??"")??s.videoSizeToQuality({width:p,height:m});if(!T)return d;const b=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,g={id:f.toString(),quality:T,bitrate:h.bitrate/1e3,size:{width:p,height:m},fps:b};return this.trackLevels.set(f,{track:g,level:h}),d.push(g),d},[]))),t.availableVideoTracks$),n(at(this.hls,Se.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){const d=[];for(const h of l.subtitleTracks){const f=h.name,p=h.attrs.URI||"",m=h.lang,T="internal";d.push({id:f,url:p,language:m,type:T})}e.internalTextTracks.startTransitionTo(d)}}),n(at(this.hls,Se.Events.LEVEL_LOADING).pipe(s.map(({url:l})=>Te(l))),t.hostname$),this.subscription.add(ke(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));const o=l=>Array.from(this.trackLevels.values()).find(({level:d})=>d===l)?.track,c=at(this.hls,Se.Events.LEVEL_SWITCHED).pipe(s.map(({level:l})=>o(this.hls.levels[l])));c.pipe(s.filter(s.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ke(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),l=>{if(s.isNullable(l))return;const d=this.trackLevels.get(l.id)?.level;if(!d)return;const h=this.hls.levels.indexOf(d),f=this.hls.currentLevel,p=this.hls.levels[f];!p||d.bitrate>p.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:c,onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=s.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(u.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!==B.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&a.state===I.Requested&&this.seek(a.position),t){case exports.PlaybackState.STOPPED:switch(e){case B.STOPPED:break;case B.READY:case B.PLAYING:case B.PAUSED:this.stop();break;default:s.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case B.STOPPED:this.prepare();break;case B.READY:case B.PLAYING:case B.PAUSED:break;default:s.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case B.PLAYING:break;case B.STOPPED:this.prepare();break;case B.READY:case B.PAUSED:this.playIfAllowed();break;default:s.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case B.PAUSED:break;case B.STOPPED:this.prepare();break;case B.READY:this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case B.PLAYING:this.pause();break;default:s.assertNever(e)}break;default:s.assertNever(t)}};prepare(){this.videoState.startTransitionTo(B.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(B.PLAYING),await je(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(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(B.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(B.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const hi="X-Playback-Duration";var fi=async r=>{const e=await ut(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 Qa=r=>{let e=null;if(r.QUALITY&&(e=$t(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},Wa=(r,e)=>{const t=r.split(`
46
+ `),i=[],a=[];for(let n=0;n<t.length;n++){const o=t[n],c=o.match(/^#EXT-X-STREAM-INF:(.+)/),u=o.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!u)){if(c){const l=Object.fromEntries(c[1].split(",").map(b=>b.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,h=Qa(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const p=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let m;if(l.RESOLUTION){const[b,g]=l.RESOLUTION.split("x").map(C=>parseInt(C,10));b&&g&&(m={width:b,height:g})}const T=new URL(t[++n],e).toString();h&&i.push({id:d,quality:h,url:T,bandwidth:f,size:m,fps:p})}if(u){const l=Object.fromEntries(u[1].split(",").map(p=>p.split("=")).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,f=l.NAME;d&&h&&a.push({type:"internal",id:h,label:f,language:h,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},Ja=r=>new Promise(e=>{setTimeout(()=>{e()},r)});let Mt=0;const Jt=async(r,e=r,t)=>{const a=await(await ut(r)).text();Mt+=1;try{const{qualityManifests:n,textTracks:o}=Wa(a,e);return{qualityManifests:n,textTracks:o}}catch{if(Mt<=t.manifestRetryMaxCount)return await Ja(s.getExponentialDelay(Mt-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Jt(r,e,t)}return{qualityManifests:[],textTracks:[]}};var U;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(U||(U={}));class Xa{subscription=new s.Subscription;videoState=new q(U.STOPPED);video;params;textTracksManager=new xe;masterManifest;manifests$=new s.ValueSubject([]);maxSeekBackTime$;liveOffset=new zt;manifestStartTime$=new s.ValueSubject(void 0);constructor(e){this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url},Jt(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:s.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(Te(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?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo(this.masterManifest),o.find(u=>u.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=He(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,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(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY),this.videoState.getState()===U.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(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&s.isNonNullable(l.to)){const h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===U.CHANGING_MANIFEST&&this.videoState.setState(u.to),c&&c.state===I.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:u})=>this.params.output.liveTime$.next(c+u*1e3),i)),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:u,quality:l,size:d,bandwidth:h,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.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),Oe(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:c,min:u}=t?.to??i??{};for(const[l,d]of[[c,"mq"],[u,"lq"]]){const h=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,h)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?J.DASH_CMAF_OFFSET_P:J.OFFSET_P,o=fe(a.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),fi(o).then(c=>{if(!s.isNullable(c))this.maxSeekBackTime$.next(c);else{const u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(s.isNullable(u)||!isFinite(u))try{ut(o).then(l=>l.text()).then(l=>{const d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){const h=new URL(d,o).toString();fi(h).then(f=>{s.isNullable(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),w(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(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(U.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(t===U.STOPPED){this.videoState.startTransitionTo(U.READY),this.prepare();return}if(n||o||c){const d=this.videoState.getState();this.videoState.setState(U.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),l.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!==exports.PlaybackState.PAUSED&&l.state===I.Requested){this.videoState.startTransitionTo(U.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case U.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed());return;case U.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(U.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to===exports.PlaybackState.PAUSED&&(w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case U.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var j;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(j||(j={}));class Ka{subscription=new s.Subscription;videoState=new q(j.STOPPED);video;params;textTracksManager=new xe;masterManifest;manifests$=new s.ValueSubject([]);constructor(e){this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video),this.masterManifest={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(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Jt(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),n=a?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!a&&t.startTransitionTo(this.masterManifest),o.find(u=>u.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=He(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u));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(ht(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===j.READY&&this.videoState.setState(j.READY),this.videoState.getState()===j.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&s.isNonNullable(l.to)){const h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);const f=this.manifests$.getValue().find(p=>p.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url));const p=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(p!==m){const T=this.params.output.element$.getValue();T&&(this.params.desiredState.playbackRate.setState(p),T.playbackRate=p)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===j.CHANGING_MANIFEST&&this.videoState.setState(u.to),c.state===I.Requested&&this.seek(c.position)},i))),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:u,quality:l,size:d,bandwidth:h,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!s.isIOS()||!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 u=0;u<c.length;u++)c[u].mode="hidden"},i))}const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.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),Oe(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:n,min:o}=t?.to??i??{};for(const[c,u]of[[n,"mq"],[o,"lq"]]){const l=String(parseFloat(c||""));u&&c&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(j.PAUSED),w(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(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==j.STOPPED&&(this.videoState.startTransitionTo(j.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(j.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(t===j.STOPPED){this.videoState.startTransitionTo(j.READY),this.prepare();return}if(n||o||c){const d=this.videoState.getState();this.videoState.setState(j.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:h}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),l.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:h*1e3,forcePrecise:!0});return}switch(a?.to!==exports.PlaybackState.PAUSED&&l.state===I.Requested&&this.seek(l.position),t){case j.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(j.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed());return;case j.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(j.PAUSED),this.video.pause()):a?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case j.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed()):a?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case j.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var G;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(G||(G={}));class Za{subscription=new s.Subscription;videoState=new q(G.STOPPED);video;trackUrls={};params;textTracksManager=new xe;constructor(e){this.params=e,this.video=Fe(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=He(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,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(ht(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY);const c=this.params.desiredState.videoTrack.getTransition();if(c&&s.isNonNullable(c.to)){this.params.desiredState.videoTrack.setState(c.to),this.params.output.currentVideoTrack$.next(this.trackUrls[c.to.id].track);const u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){const d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()===G.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),Oe(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;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=jt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),w(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!==G.STOPPED&&(this.videoState.startTransitionTo(G.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(G.STOPPED),w(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!==G.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(o){const{currentTime:u}=this.video;this.prepare(),c.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:u*1e3,forcePrecise:!0}),o.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[o.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==exports.PlaybackState.PAUSED&&c.state===I.Requested&&this.seek(c.position),e){case G.READY:t===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const a=Object.values(this.trackUrls).find(c=>!s.isInvariantQuality(c.track.quality)&&s.isLowerOrEqual(c.track.quality,e))?.track,n=this.params.desiredState.videoTrack.getState()?.id,o=this.trackUrls[n??"0"]?.track;if(a&&o&&s.isHigherOrEqual(o.quality,a.quality)&&(t=a),!t){const c=Object.values(this.trackUrls).filter(l=>!s.isInvariantQuality(l.track.quality)&&s.isHigher(l.track.quality,e)),u=c.length;u&&(t=c[u-1].track)}t&&(i=t.quality)}else if(!e){const a=Object.values(this.trackUrls).map(n=>n.track);t=Pt(a,{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)),this.params.output.autoVideoTrackLimits$.next({max:i})}}const pi=["stun:videostun.mycdn.me:80"],er=1e3,tr=3,_t=()=>null;class ir{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=_t;externalStopCallback=_t;externalErrorCallback=_t;constructor(e,t){this.options=this.normalizeOptions(t);const 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:pi}]};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),er)}normalizeOptions(e={}){const t={stunServerList:pi,maxRetryNumber:tr,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var H;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(H||(H={}));class sr{subscription;params;log;video;videoState=new q(H.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=Fe(e.container),this.liveStreamClient=new ir(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),Oe(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=He(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===H.READY&&this.videoState.setState(H.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ue(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case H.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case H.READY:break;case H.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case H.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return 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(Te(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,w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(H.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:s.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){je(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),w(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!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(H.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case H.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(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 Fi=s.getCurrentBrowser().device===s.CurrentClientDevice.Android,At=document.createElement("video"),ar='video/mp4; codecs="avc1.42000a,mp4a.40.2"',rr='video/mp4; codecs="hev1.1.6.L93.B0"',Oi='video/webm; codecs="vp09.00.10.08"',Ui='video/webm; codecs="av01.0.00M.08"',nr='audio/mp4; codecs="mp4a.40.2"',or='audio/webm; codecs="opus"',Ve={mms:Mi(),mse:Ba(),hls:!!(At.canPlayType?.("application/x-mpegurl")||At.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},re={mp4:!!At.canPlayType?.("video/mp4"),webm:!!At.canPlayType?.("video/webm"),cmaf:!0},ve={h264:!!Ie()?.isTypeSupported?.(ar),h265:!!Ie()?.isTypeSupported?.(rr),vp9:!!Ie()?.isTypeSupported?.(Oi),av1:!!Ie()?.isTypeSupported?.(Ui),aac:!!Ie()?.isTypeSupported?.(nr),opus:!!Ie()?.isTypeSupported?.(or)},rt=(ve.h264||ve.h265)&&ve.aac;var Le;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Le||(Le={}));var Ae;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(Ae||(Ae={}));let Be;const cr=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:Ui}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Oi}})]);Be={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{cr()}catch(r){console.error(r)}const dt=Ve.hls&&re.mp4,lr=()=>Object.keys(ve).filter(r=>ve[r]),ur=(r,e=!1,t=!1)=>{const i=Ve.mse||Ve.mms&&t;return r.filter(a=>{switch(a){case exports.VideoFormat.DASH_SEP:return i&&re.mp4&&rt;case exports.VideoFormat.DASH_WEBM:return i&&re.webm&&ve.vp9&&ve.opus;case exports.VideoFormat.DASH_WEBM_AV1:return i&&re.webm&&ve.av1&&ve.opus;case exports.VideoFormat.DASH_LIVE:return Ve.mse&&re.mp4&&rt;case exports.VideoFormat.DASH_LIVE_CMAF:return i&&re.mp4&&rt&&re.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return i&&re.mp4&&rt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return dt||e&&Ve.mse&&re.mp4&&rt;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return dt;case exports.VideoFormat.MPEG:return re.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ve.webrtc&&Ve.ws&&ve.h264&&(re.mp4||re.webm);default:return s.assertNever(a)}})},nt=r=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(r){case Le.VP9:return[e,t];case Le.AV1:return[t,e];case Le.NONE:return[];case Le.SMOOTH:return Be?Be[t].smooth?[t,e]:Be[e].smooth?[e,t]:[t,e]:[e,t];case Le.POWER_EFFICIENT:return Be?Be[t].powerEfficient?[t,e]:Be[e].powerEfficient?[e,t]:[t,e]:[e,t];default:s.assertNever(r)}return[e,t]},dr=({webmCodec:r,androidPreferredFormat:e})=>{if(Fi)switch(e){case Ae.MPEG:return[exports.VideoFormat.MPEG,...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case Ae.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case Ae.DASH:return[...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return dt?[...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...nt(r),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},hr=({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(Fi)switch(r){case Ae.DASH:{c=n;break}case Ae.HLS:case Ae.MPEG:{c=o;break}}else dt?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 fr=r=>new s.Observable(e=>{const t=new s.Subscription,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(s.map(({from:l,to:d})=>`${l}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$.pipe(s.map(({type:l})=>l!==void 0)),o=new s.Subject;let c=0,u="unknown";return t.add(i.subscribe(l=>{c&&window.clearTimeout(c),u=l,c=window.setTimeout(()=>o.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(c),u="unknown",c=0})),t.add(n.subscribe(l=>{c&&(window.clearTimeout(c),c=0,l&&(c=window.setTimeout(()=>o.next(u),r.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const pr={chunkDuration:5e3,maxParallelRequests:5};class mr{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=ur([...hr(this.params.tuning),...dr(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).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!==I.None;if(this.params.desiredState.seekState.setState({state:I.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 Z.SCREEN:return this.createScreenProvider(t);case Z.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_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const c=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[exports.VideoFormat.HLS_ONDEMAND]||t[exports.VideoFormat.HLS]);return s.assertNonNullable(c),new Ga({...o,source:c,sourceHls:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new qa({...o,source:c})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),dt||!this.params.tuning.useHlsJs?new Ka({...o,source:c}):new za({...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 Xa({...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 Za({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Is({...o,source:c,config:{...pr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new sr({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 ns({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()?Z.CHROMECAST:Z.SCREEN}chooseFormat(e){switch(e){case Z.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Z.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return s.assertNever(e)}}skipFormat(e){switch(e){case Z.SCREEN:return this.screenFormatsIterator.next();case Z.CHROMECAST:return this.chromecastFormatsIterator.next();default:return s.assertNever(e)}}handleNoFormatsError(e){switch(e){case Z.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Z.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$,fr({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===Z.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Z.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),u=i<this.params.tuning.providerErrorLimit;c&&(o&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(n??Z.SCREEN)}})),e}}const Sr=5e3,bi="one_video_throughput",gi="one_video_rtt",ct=window.navigator.connection,yi=()=>{const r=ct?.downlink;if(s.isNonNullable(r)&&r!==10)return r*1e3},vi=()=>{const r=ct?.rtt;if(s.isNonNullable(r)&&r!==3e3)return r},Ti=(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(bi)||(e.useBrowserEstimation?yi():void 0)||Sr,i=lt.load(gi)??(e.useBrowserEstimation?vi():void 0)??0;if(this.throughput$=new s.ValueSubject(t),this.rtt$=new s.ValueSubject(i),this.rttAdjustedThroughput$=new s.ValueSubject(Ti(t,i,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(i,1,e),e.useBrowserEstimation){const a=()=>{const o=yi();o&&this.throughput.next(o);const c=vi();s.isNonNullable(c)&&this.rtt.next(c)};ct&&"onchange"in ct&&this.subscription.add(s.fromEvent(ct,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{s.safeStorage.set(bi,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{s.safeStorage.set(gi,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})=>Ti(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(),u=o-t,l=c-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,n=s.now(),o=0,c=s.now();const u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:h})=>{if(d)!t&&this.addRawSpeed(a,s.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(s.now()-c<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=h.byteLength;else{const p=c-n;p&&this.addRawSpeed(o,p,1,t),o=h.byteLength,n=s.now()}c=s.now()}else a+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&s.now()-c>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,s.now()-c,this.concurrentDownloads.size),o=0,c=s.now());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(lt.sanityCheck(e,t,a)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=s.safeStorage.get(e);if(s.isNonNullable(t))return parseInt(t,10)??void 0}}const Ei={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,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:s.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},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,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},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:Le.VP9,androidPreferredFormat:Ae.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},br=r=>({...s.fillWithDefault(r,Ei),configName:[...r.configName??[],...Ei.configName]});var ki=({seekState:r,position$:e})=>s.merge(r.stateChangeEnded$.pipe(s.map(({to:t})=>t.state===I.None?void 0:(t.position??NaN)/1e3),s.filter(s.isNonNullable)),e.pipe(s.filter(()=>r.getState().state===I.None))),gr=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return s.assertNonNullable(e,`Wrong container or containerId {${r.container}}`),e};const yr=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(s.filter(a=>a.length>0),s.once()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};class vr{subscription=new s.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new s.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new q(exports.PlaybackState.STOPPED),seekState:new q({state:I.None}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({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:Ss};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=br(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new es({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 u=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:s.ErrorCategory.WTF,message:d,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.domContainer=gr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new mr({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:I.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();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(s.filter(i=>i.length>0),s.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),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 yr(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===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(){if(!this.providerContainer)return 0;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===I.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===I.Requested?this.desiredState.seekState.setState({...o,state:I.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===I.Applying&&(this.desiredState.seekState.setState({state:I.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,u)=>s.isInvariantQuality(c)?1:s.isInvariantQuality(u)?-1:s.isHigher(u,c)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const c={};for(const u of o)u.fps&&(c[u.quality]=u.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:ki({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(s.map(({isLive:o,position:c,isLowLatency:u})=>{const l=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(c)<l/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:u})=>o&&(Math.abs(u)-Math.abs(c))*1e3<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(ki({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(),u=e.providerOutput.element$.getValue(),l=this.chromecastInitializer.castState$.getValue();let d;l===exports.ChromecastState.CONNECTED?d=exports.Surface.SECOND_SCREEN:u?o?d=exports.Surface.PIP:c?d=exports.Surface.FULLSCREEN:d=exports.Surface.INLINE:d=exports.Surface.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}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;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Pt(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),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),ms(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ps(t)),this.providerContainer.current$.subscribe(({type:t})=>gt("provider",t)),e.duration$.subscribe(t=>gt("duration",t)),e.availableVideoTracks$.pipe(s.filter(t=>!!t.length),s.once()).subscribe(t=>gt("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)),gt("codecs",lr())}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))}setVideoTrackIdByQuality(e,t){const i=e.find(a=>a.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const Tr=`@vkontakte/videoplayer-core@${wi}`;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=vr;exports.SDK_VERSION=Tr;exports.VERSION=wi;