@vkontakte/videoplayer-core 2.0.103-dev.620e0c0f.0 → 2.0.103-dev.9b9f4181.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.cjs.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.103-dev.620e0c0f.0
3
- * Fri, 31 May 2024 07:37:31 GMT
2
+ * @vkontakte/videoplayer-core v2.0.103-dev.9b9f4181.0
3
+ * Mon, 03 Jun 2024 08:01:27 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-103/doc/
5
5
  */
6
- "use strict";var zi=Object.create;var Kt=Object.defineProperty;var Wi=Object.getOwnPropertyDescriptor;var Qi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,Xi=Object.prototype.hasOwnProperty;var Ki=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qi(e))!Xi.call(a,r)&&r!==t&&Kt(a,r,{get:()=>e[r],enumerable:!(i=Wi(e,r))||i.enumerable});return a};var Zi=(a,e,t)=>(t=a!=null?zi(Ji(a)):{},Ki(e||!a||!a.__esModule?Kt(t,"default",{value:a,enumerable:!0}):t,a));var s=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const Ai="2.0.103-dev.620e0c0f.0";exports.PlaybackState=void 0;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(a){a.MPEG="MPEG",a.DASH="DASH_SEP",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ee;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ee||(ee={}));exports.ChromecastState=void 0;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var I;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(I||(I={}));exports.Surface=void 0;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(exports.Surface||(exports.Surface={}));var es=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class ts{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),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||es("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(r=>{switch(r.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(r.sessionState)}})).add(s.merge(s.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(s.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),s.map(r=>r.castState)),s.observableFrom([i.getCastState()])).pipe(s.filterChanged(),s.map(is),s.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{const n=r===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(r===exports.ChromecastState.CONNECTED?s.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}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(r){this.errorEvent$.next({id:"ChromecastInitializer",category:s.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}}const is=a=>{switch(a){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(a)}};var X;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(X||(X={}));var me=(a,e=0,t=X.OFFSET_P)=>{switch(t){case X.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case X.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case X.DASH_CMAF_OFFSET_P:{const i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:s.assertNever(t)}return a};const Zt=(a,e)=>{switch(e){case X.OFFSET_P:return NaN;case X.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case X.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:s.assertNever(e)}};var A=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class z{state;prevState;transition;transitionStarted$=new s.Subject;transitionEnded$=new s.Subject;transitionUpdated$=new s.Subject;forceChanged$=new s.Subject;stateChangeStarted$=s.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=s.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||s.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const ss=a=>{switch(a){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(a)}};var L;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(L||(L={}));const as=5,rs=5,ns=500,ei=7e3;class os{subscription=new s.Subscription;loadMediaTimeoutSubscription=new s.Subscription;videoState=new z(L.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(ss(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(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(s.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new s.Subject;e.add(r.pipe(s.debounce(ns)).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)>as)&&r.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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.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<rs&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.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(L.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),A(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===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===L.READY&&this.videoState.setState(L.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.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,r,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,r="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,r="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,r="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,r="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=me(l.url),r="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,r);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((r,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()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:s.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}).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(),r=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!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!t){if(r?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&e!==L.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:s.assertNever(e)}break}default:s.assertNever(i)}}}}const Gt=a=>{a.removeAttribute("src"),a.load()},cs=a=>{try{a.pause(),a.playbackRate=0,Gt(a),a.remove()}catch(e){console.error(e)}};class ls{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 ls,Ue=a=>{let e=a.querySelector("video");const t=!!e;return e?Gt(e):(e=document.createElement("video"),a.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},He=a=>{const e=Ft.get(a);Ft.delete(a),e?Gt(a):cs(a)},we=(a,e,t,{equal:i=(o,c)=>o===c,changed$:r,onError:n}={})=>{const o=a.getState(),c=e(),u=s.isNullable(r),l=new s.Subscription;return r&&l.add(r.subscribe(d=>{const h=a.getState();i(d,h)&&a.setState(d)},n)),i(c,o)||(t(o),u&&a.setState(o)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},n)),l},ft=(a,e,t)=>we(e,()=>a.loop,i=>{s.isNonNullable(i)&&(a.loop=i)},{onError:t}),je=(a,e,t,i)=>we(e,()=>({muted:a.muted,volume:a.volume}),r=>{s.isNonNullable(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,n)=>r===n||r?.muted===n?.muted&&r?.volume===n?.volume,changed$:t,onError:i}),tt=(a,e,t,i)=>we(e,()=>a.playbackRate,r=>{s.isNonNullable(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),us=a=>["__",a.language,a.label].join("|"),ds=(a,e)=>{if(a.id===e)return!0;const[t,i,r]=e.split("|");return a.language===i&&a.label===r};class Ne{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 r=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(we(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:r})),this.subscription.add(we(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:r})),this.subscription.add(we(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:r})),this.subscription.add(we(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,r)=>i.length===r.length&&i.every(({id:n},o)=>n===r[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 r=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),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 r=i;s.isNonNullable(t.align)&&(r.align=t.align),s.isNonNullable(t.position)&&(r.position=t.position),s.isNonNullable(t.size)&&(r.size=t.size),s.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){s.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ne.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id?e.id:us(e),n=this.externalTracks.has(r),o=r.includes("auto");return n?{id:r,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(r)?.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:r,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.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)||!ds(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 qt{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 wi=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ti=a=>{const e=wi(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},hs=a=>{const e=wi(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},fs=3;var ps=(a,e,t=fs)=>{let i=0,r=0;for(let n=0;n<a.length;n++){const o=a.start(n),c=a.end(n);if(o<=e&&e<=c){if(i=o,r=c,!t)return{from:i,to:r};for(let u=n-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=n+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};const Ye=a=>{const e=P=>s.fromEvent(a,P).pipe(s.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=s.merge(...t.map(P=>s.fromEvent(a,P))).pipe(s.map(P=>P.type==="ended"?a.readyState<2:a.readyState<3),s.filterChanged()),r=s.merge(s.fromEvent(a,"progress"),s.fromEvent(a,"timeupdate")).pipe(s.map(()=>ps(a.buffered,a.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(a,"volumechange").pipe(s.map(()=>({muted:a.muted,volume:a.volume}))),u=s.fromEvent(a,"ratechange").pipe(s.map(()=>a.playbackRate)),l=s.fromEvent(a,"error").pipe(s.filter(()=>!!(a.error||a.played.length)),s.map(()=>{const P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:s.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:a.error??void 0}})),d=s.fromEvent(a,"timeupdate").pipe(s.map(()=>a.currentTime)),h=new s.Subject,f=.3;let p;d.subscribe(P=>{a.loop&&s.isNonNullable(p)&&s.isNonNullable(P)&&p>=a.duration-f&&P<=f&&h.next(p),p=P});const m=s.fromEvent(a,"enterpictureinpicture"),T=s.fromEvent(a,"leavepictureinpicture"),b=new s.ValueSubject(hs(a));m.subscribe(()=>b.next(!0)),T.subscribe(()=>b.next(!1));const y=new s.ValueSubject(ti(a));return s.fromEvent(a,"fullscreenchange").pipe(s.map(()=>ti(a))).subscribe(y),{playing$:o,pause$:e("pause").pipe(s.filter(()=>!a.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(a,"durationchange").pipe(s.map(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:c,playbackRateState$:u,inPiP$:b,inFullscreen$:y}};var Pt=a=>{switch(a){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 zt=!1,$e={};const ms=a=>{zt=a},Ss=()=>{$e={}},bs=a=>{a($e)},yt=(a,e)=>{zt&&($e.meta=$e.meta??{},$e.meta[a]=e)};class ve{name;constructor(e){this.name=e}next(e){if(!zt)return;$e.series=$e.series??{};const t=$e.series[this.name]??[];t.push([Date.now(),e]),$e.series[this.name]=t}}var _e;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(_e||(_e={}));const gs=new ve("best_bitrate"),ys=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class vs{last;history={};recordSelection(e){this.history[e.id]=s.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Ts='Assertion "ABR Tracks is empty array" failed',Ct=(a,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:u,history:l,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{s.assertNotEmptyArray(a,Ts);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=a.filter(k=>!s.isInvariantQuality(k.quality)).sort((k,w)=>s.isHigher(k.quality,w.quality)?-1:1),y=b.at(-1)?.quality,C=b.at(0)?.quality,P=s.isNullable(r)||s.isNonNullable(r.min)&&s.isNonNullable(r.max)&&s.isLower(r.max,r.min)||s.isNonNullable(r.min)&&C&&s.isHigher(r.min,C)||s.isNonNullable(r.max)&&y&&s.isLower(r.max,y),g=T*ys(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},B=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]=_e.Buffer,!1):!!d&&s.isHigherOrEqual(k.quality,d)?(E[k.quality]=_e.DroppedFramesLimit,!1):P||(s.isNullable(r.max)||s.isLowerOrEqual(k.quality,r.max))&&(s.isNullable(r.min)||s.isHigherOrEqual(k.quality,r.min))?!0:(E[k.quality]=_e.FitsQualityLimits,!1):(E[k.quality]=_e.FitsThroughput,!1):(E[k.quality]=_e.FitsContainer,!1))[0];B&&B.bitrate&&gs.next(B.bitrate);const R=B??b[Math.ceil((b.length-1)/2)]??a[0];R.quality!==l?.last?.quality&&h({message:`
6
+ "use strict";var Wi=Object.create;var Zt=Object.defineProperty;var Qi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Xi=Object.getPrototypeOf,Ki=Object.prototype.hasOwnProperty;var Zi=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ji(e))!Ki.call(a,r)&&r!==t&&Zt(a,r,{get:()=>e[r],enumerable:!(i=Qi(e,r))||i.enumerable});return a};var es=(a,e,t)=>(t=a!=null?Wi(Xi(a)):{},Zi(e||!a||!a.__esModule?Zt(t,"default",{value:a,enumerable:!0}):t,a));var s=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const wi="2.0.103-dev.9b9f4181.0";exports.PlaybackState=void 0;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(a){a.MPEG="MPEG",a.DASH="DASH_SEP",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ee;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ee||(ee={}));exports.ChromecastState=void 0;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var I;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(I||(I={}));exports.Surface=void 0;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(exports.Surface||(exports.Surface={}));var ts=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class is{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),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||ts("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(r=>{switch(r.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(r.sessionState)}})).add(s.merge(s.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(s.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),s.map(r=>r.castState)),s.observableFrom([i.getCastState()])).pipe(s.filterChanged(),s.map(ss),s.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{const n=r===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(r===exports.ChromecastState.CONNECTED?s.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}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(r){this.errorEvent$.next({id:"ChromecastInitializer",category:s.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}}const ss=a=>{switch(a){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(a)}};var X;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(X||(X={}));var me=(a,e=0,t=X.OFFSET_P)=>{switch(t){case X.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case X.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case X.DASH_CMAF_OFFSET_P:{const i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:s.assertNever(t)}return a};const ei=(a,e)=>{switch(e){case X.OFFSET_P:return NaN;case X.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case X.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:s.assertNever(e)}};var A=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class z{state;prevState;transition;transitionStarted$=new s.Subject;transitionEnded$=new s.Subject;transitionUpdated$=new s.Subject;forceChanged$=new s.Subject;stateChangeStarted$=s.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=s.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||s.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const as=a=>{switch(a){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(a)}};var L;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(L||(L={}));const rs=5,ns=5,os=500,ti=7e3;class cs{subscription=new s.Subscription;loadMediaTimeoutSubscription=new s.Subscription;videoState=new z(L.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(as(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(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(s.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new s.Subject;e.add(r.pipe(s.debounce(os)).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)>rs)&&r.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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.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<ns&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.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(L.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),A(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===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===L.READY&&this.videoState.setState(L.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.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,r,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,r="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,r="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,r="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,r="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=me(l.url),r="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,r);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((r,n)=>{this.loadMediaTimeoutSubscription.add(s.timeout(ti).subscribe(()=>n(`timeout(${ti})`)))});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()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:s.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}).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(),r=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!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!t){if(r?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&e!==L.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:s.assertNever(e)}break}default:s.assertNever(i)}}}}const qt=a=>{a.removeAttribute("src"),a.load()},ls=a=>{try{a.pause(),a.playbackRate=0,qt(a),a.remove()}catch(e){console.error(e)}};class us{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 Ot=window.WeakMap?new WeakMap:new us,Ue=a=>{let e=a.querySelector("video");const t=!!e;return e?qt(e):(e=document.createElement("video"),a.appendChild(e)),Ot.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},He=a=>{const e=Ot.get(a);Ot.delete(a),e?qt(a):ls(a)},we=(a,e,t,{equal:i=(o,c)=>o===c,changed$:r,onError:n}={})=>{const o=a.getState(),c=e(),u=s.isNullable(r),l=new s.Subscription;return r&&l.add(r.subscribe(d=>{const h=a.getState();i(d,h)&&a.setState(d)},n)),i(c,o)||(t(o),u&&a.setState(o)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},n)),l},pt=(a,e,t)=>we(e,()=>a.loop,i=>{s.isNonNullable(i)&&(a.loop=i)},{onError:t}),je=(a,e,t,i)=>we(e,()=>({muted:a.muted,volume:a.volume}),r=>{s.isNonNullable(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,n)=>r===n||r?.muted===n?.muted&&r?.volume===n?.volume,changed$:t,onError:i}),tt=(a,e,t,i)=>we(e,()=>a.playbackRate,r=>{s.isNonNullable(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ds=a=>["__",a.language,a.label].join("|"),hs=(a,e)=>{if(a.id===e)return!0;const[t,i,r]=e.split("|");return a.language===i&&a.label===r};class Ne{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 r=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(we(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:r})),this.subscription.add(we(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:r})),this.subscription.add(we(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:r})),this.subscription.add(we(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,r)=>i.length===r.length&&i.every(({id:n},o)=>n===r[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 r=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),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 r=i;s.isNonNullable(t.align)&&(r.align=t.align),s.isNonNullable(t.position)&&(r.position=t.position),s.isNonNullable(t.size)&&(r.size=t.size),s.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){s.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ne.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id?e.id:ds(e),n=this.externalTracks.has(r),o=r.includes("auto");return n?{id:r,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(r)?.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:r,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.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)||!hs(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 $i=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ii=a=>{const e=$i(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},fs=a=>{const e=$i(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},ps=3;var ms=(a,e,t=ps)=>{let i=0,r=0;for(let n=0;n<a.length;n++){const o=a.start(n),c=a.end(n);if(o<=e&&e<=c){if(i=o,r=c,!t)return{from:i,to:r};for(let u=n-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=n+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};const Ye=a=>{const e=P=>s.fromEvent(a,P).pipe(s.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=s.merge(...t.map(P=>s.fromEvent(a,P))).pipe(s.map(P=>P.type==="ended"?a.readyState<2:a.readyState<3),s.filterChanged()),r=s.merge(s.fromEvent(a,"progress"),s.fromEvent(a,"timeupdate")).pipe(s.map(()=>ms(a.buffered,a.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(a,"volumechange").pipe(s.map(()=>({muted:a.muted,volume:a.volume}))),u=s.fromEvent(a,"ratechange").pipe(s.map(()=>a.playbackRate)),l=s.fromEvent(a,"error").pipe(s.filter(()=>!!(a.error||a.played.length)),s.map(()=>{const P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:s.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:a.error??void 0}})),d=s.fromEvent(a,"timeupdate").pipe(s.map(()=>a.currentTime)),h=new s.Subject,f=.3;let p;d.subscribe(P=>{a.loop&&s.isNonNullable(p)&&s.isNonNullable(P)&&p>=a.duration-f&&P<=f&&h.next(p),p=P});const m=s.fromEvent(a,"enterpictureinpicture"),T=s.fromEvent(a,"leavepictureinpicture"),b=new s.ValueSubject(fs(a));m.subscribe(()=>b.next(!0)),T.subscribe(()=>b.next(!1));const y=new s.ValueSubject(ii(a));return s.fromEvent(a,"fullscreenchange").pipe(s.map(()=>ii(a))).subscribe(y),{playing$:o,pause$:e("pause").pipe(s.filter(()=>!a.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(a,"durationchange").pipe(s.map(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:c,playbackRateState$:u,inPiP$:b,inFullscreen$:y}};var Ct=a=>{switch(a){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 Wt=!1,$e={};const Ss=a=>{Wt=a},bs=()=>{$e={}},gs=a=>{a($e)},vt=(a,e)=>{Wt&&($e.meta=$e.meta??{},$e.meta[a]=e)};class ve{name;constructor(e){this.name=e}next(e){if(!Wt)return;$e.series=$e.series??{};const t=$e.series[this.name]??[];t.push([Date.now(),e]),$e.series[this.name]=t}}var _e;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(_e||(_e={}));const ys=new ve("best_bitrate"),vs=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Ts{last;history={};recordSelection(e){this.history[e.id]=s.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Es='Assertion "ABR Tracks is empty array" failed',Dt=(a,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:u,history:l,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{s.assertNotEmptyArray(a,Es);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=a.filter(k=>!s.isInvariantQuality(k.quality)).sort((k,w)=>s.isHigher(k.quality,w.quality)?-1:1),y=b.at(-1)?.quality,C=b.at(0)?.quality,P=s.isNullable(r)||s.isNonNullable(r.min)&&s.isNonNullable(r.max)&&s.isLower(r.max,r.min)||s.isNonNullable(r.min)&&C&&s.isHigher(r.min,C)||s.isNonNullable(r.max)&&y&&s.isLower(r.max,y),g=T*vs(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},B=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]=_e.Buffer,!1):!!d&&s.isHigherOrEqual(k.quality,d)?(E[k.quality]=_e.DroppedFramesLimit,!1):P||(s.isNullable(r.max)||s.isLowerOrEqual(k.quality,r.max))&&(s.isNullable(r.min)||s.isHigherOrEqual(k.quality,r.min))?!0:(E[k.quality]=_e.FitsQualityLimits,!1):(E[k.quality]=_e.FitsThroughput,!1):(E[k.quality]=_e.FitsContainer,!1))[0];B&&B.bitrate&&ys.next(B.bitrate);const R=B??b[Math.ceil((b.length-1)/2)]??a[0];R.quality!==l?.last?.quality&&h({message:`
7
7
  [available tracks]
8
8
  ${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
9
  `)}
@@ -34,13 +34,13 @@
34
34
  [selected track] ${R?.quality}
35
35
  `});const V=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&&!V&&l.recordSelection(R),V&&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 ke=a=>new URL(a).hostname;const ii=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var Ge=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!ii(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return ii(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function te(){return s.now()}function $i(a){return te()-a}function si(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=o=>i.test(o);return{resolve:(o,c,u=!1)=>{r(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 Es(a,e,t){const i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Tt(a,e,t,i){const r=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 W;if(N<T){W=T-N,setTimeout(b,W);return}T*=2,T>m&&(T=m),o&&o.abort(),o=new r,F()};const y=N=>(n=N,w),C=N=>(h=N,w),P=()=>(p="json",w),g=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,h&&h(),t&&t()}},E=N=>(f=N,w),F=()=>{d=te(),o=new r,o.open("get",a);let N=0,W,K=0;const de=()=>(s.assertNonNullable(d),Math.max(d,Math.max(W||0,K||0)));if(n&&o.addEventListener("progress",$=>{const _=te();n.updateChunk&&$.loaded>N&&(n.updateChunk(de(),$.loaded-N),N=$.loaded,W=_)}),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.response.byteLength-N;_&&n.updateChunk&&n.updateChunk(de(),_)}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&&(K=te(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),w},w={withBitrateReporting:y,withParallel:E,withJSONResponse:P,withRetryCount:N=>(l=N,w),withRetryInterval:(N,W)=>(s.isNonNullable(N)&&(T=N),s.isNonNullable(W)&&(m=W),w),withTimeout:N=>(c=N,w),withFinally:C,send:F,abort:()=>{o&&(o.abort(),o=void 0),u=!0,h&&h()}};return w}const ks=100,As=2e3,ws=500;let $s=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>As){let i=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,r+=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;r+=u,n.start=t,n.bytes-=u}}}if(r>0&&i>0){const n=r*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(r)}/${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>ks&&(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 Ps{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,r,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,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=te(),r=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=te()-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=Tt(t,n,()=>r("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=te()}_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=te();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,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=r,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=r,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const vt=1e4,Mt=3,Cs=6e4,Ds=10,Ls=1,xs=500;class Rs{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 $s(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 r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,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)?(!r||n.bitrate>r.bitrate)&&(r=n):(!i||i.bitrate>n.bitrate)&&(i=n));return r||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:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{Es(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 Ps(Mt,vt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=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,F)=>{u&&u.abort(),u=Tt(this.urlResolver.resolve(g,!1),E,F,()=>this._retryCallback()).withTimeout(vt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mt).withFinally(()=>{u=null}).send()},p=(g,E,F)=>{s.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),E,F,()=>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 F=te()-1e4;let B=0;for(let V=0;V<this.bufferStates.length;V++){const k=this.bufferStates[V];g=Math.min(g,k.buf),k.ts<F&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${g} drop=${B} jitter=${this.sourceJitter}`);let R=g-Ls;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 F=()=>E&&E.start?E.start.length:0,B=$=>E.start[$]/1e3,R=$=>E.dur[$]/1e3,V=$=>E.fragIndex+$,k=($,_)=>({chunkIdx:V($),startTS:B($),dur:R($),discontinuity:_}),w=()=>{let $=0;if(E&&E.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=_;this.sourceJitter>1&&(J+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(J-=E.dur[se],!(J<=0));--se);$=Math.min(se,E.dur.length-1-Q),$=Math.max($,0)}return k($,!0)},N=$=>{const _=F();if(!(_<=0)){if(s.isNonNullable($)){for(let Q=0;Q<_;Q++)if(B(Q)>$)return k(Q)}return w()}},W=$=>{const _=F(),Q=$?$.chunkIdx+1:0,J=Q-E.fragIndex;if(!(_<=0)){if(!$||J<0||J-_>Ds)return t(`Resync: offset=${J} bChunks=${_} chunk=`+JSON.stringify($)),w();if(!(J>=_))return k(Q-E.fragIndex,!1)}},K=($,_,Q)=>{l&&l.abort(),l=Tt(this.urlResolver.resolve($,!0,this.lowLatency),_,Q,()=>this._retryCallback()).withTimeout(vt).withRetryCount(Mt).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,_)=>{K(g,Q=>{if(!h())return;E=Q;const J=!!E.lowLatency;J!==this.lowLatency&&T(J);let se=0;for(let Ce=0;Ce<E.dur.length;++Ce)se+=E.dur[Ce];se>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(N(_))},()=>this._handleNetworkError())},nextChunk:W}},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:F}=this.params;let B=y(e.jidxUrl),R,V,k,w,N=0,W,K,de;const $=()=>{W&&(clearTimeout(W),W=void 0);const O=Math.max(xs,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=N+O,re=te(),he=Math.min(1e4,ae-re);N=re;const Ae=()=>{l||h()&&B.seek(()=>{h()&&(N=te(),_(),$())})};he>0?W=window.setTimeout(()=>{this.paused?$():Ae()},he):Ae()},_=()=>{let O;for(;O=B.nextChunk(w);)w=O,Lt(O);const ae=B.nextChunk(k);if(ae){if(k&&ae.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?$():(C(),this._initPlayerWith(e));return}Ce(ae)}else $()},Q=(O,ae)=>{if(!h()||!this.sourceBuffer)return;let re,he,Ae;const it=ne=>{window.setTimeout(()=>{h()&&Q(O,ae)},ne)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),it(100);else{const ne=te(),De=E.currentTime;!this.paused&&E.buffered.length>1&&K===De&&ne-de>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),K!==De&&(K=De,de=ne);const fe=this._getBufferSizeSec();if(fe>30)F(`Buffered ${fe} seconds; delaying appendBuffer`),it(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:ne,buf:fe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(Se){if(Se.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Ae=this.sourceBuffer.buffered.length,Ae!==0&&(re=this.sourceBuffer.buffered.start(0),he=De,he-re>4&&this.sourceBuffer.remove(re,he-3)),it(1e3);else throw Se}}},J=()=>{V&&R&&(F([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(k)]),Q(V,function(){V=null,_()}))},se=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),Ce=O=>{h()&&p(se(O),(ae,re)=>{if(h()){if(re/=1e3,V=ae,k=O,o=O.startTS,re){const he=Math.min(10,O.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}J()}},()=>this._handleNetworkError())},Lt=O=>{h()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(O),!1)))},pt=O=>{h()&&(e.cachedHeader=O,Q(O,()=>{R=!0,J()}))};n=!0,B.seek(O=>{if(h()){if(N=te(),!O){$();return}w=O,!s.isNullable(g)||O.startTS>g?Ce(O):(k=O,_())}},g),e.cachedHeader?pt(e.cachedHeader):f(e.headerUrl,pt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s.isNonNullable(r)&&(r+=.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(r),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=te();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=te();h<c&&(o=f),c=h}}}_fetchManifest(e,t,i){this.manifestRequest=Tt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(vt).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;Ge(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,n=o=>{const c=[];return o?.length?(o.forEach((u,l)=>{u.video&&r.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))},Cs))}_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 r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),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,r=t-this.prevDroppedVideoFrames,n=1-(i-r)/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],[r])=>s.isLower(i,r)?-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(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(x||(x={}));const Ns=[x.PAUSED,x.PLAYING,x.READY],Is=[x.PAUSED,x.PLAYING,x.READY];class Bs{subscription=new s.Subscription;video;videoState=new z(x.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new Ne;droppedFramesManager=new Pi;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new qt;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:s.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=Ue(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(ke(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=Ye(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(r=>r.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(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(s.combine({zeroTime:this.zeroTime$.pipe(s.filter(s.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(ft(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(tt(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:r}})=>{const n=r&&s.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.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(r.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),He(this.video)}createLiveDashPlayer(){const e=new Rs({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(),r=!i&&s.isNonNullable(t)?t:Ct(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=r?.id,o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(o||n!==c)&&this.setVideoTrack(r),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(),r=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(me(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}_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 r of t){const n=r.name??r.index.toString(10),o=Pt(r.name)??s.videoSizeToQuality(r.video),c=r.bitrate/1e3,u={...r.video};if(!o)continue;const l={id:n,quality:o,bitrate:c,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),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:r})=>r===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(),r=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(Is.includes(e)&&(o||c)){this.prepare();return}if(r?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&Ns.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(me(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const u=r?.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(me(this.params.source.url,u))}return;default:return s.assertNever(e)}}}var Z;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Z||(Z={}));var ye;(function(a){a[a.ActiveLowLatency=0]="ActiveLowLatency",a[a.LiveWithTargetOffset=1]="LiveWithTargetOffset",a[a.LiveForwardBuffering=2]="LiveForwardBuffering",a[a.None=3]="None"})(ye||(ye={}));var Et;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Et||(Et={}));var le;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(le||(le={}));var D;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(D||(D={}));var Ze;(function(a){a.MP4="mp4",a.WEBM="webm"})(Ze||(Ze={}));var kt;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(kt||(kt={}));var Y;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));var ct=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const r=a.start(i)*1e3,n=a.end(i)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};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 r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[r];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(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ms(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Li({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(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 Dt=Li({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xi=Dt?Ms({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=Dt?xi.fetch:window.fetch;Dt?xi.Request:window.Request;const Ke=Dt?Di:window.AbortController;var Ot=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const Vs=(a,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},_s=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ri=_s?Vs:window.requestIdleCallback,Fs=16;let Ri=!1;try{Ri=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Fs}catch(a){console.error(a)}class Os{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 r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};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:r}of this.queue)r(!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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:s.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class ue{source;boxParser;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e,t){this.source=e,this.boxParser=t,this.children=[];const i=this.readUint32();this.size32=i<=e.buffer.byteLength?i: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[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 ue{}class Us extends ue{majorBrand;minorVersion;compatibleBrands;constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){const r=this.readString(4);this.compatibleBrands.push(r),i-=4}}}class Hs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class js extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ys extends ue{data;constructor(e,t){super(e,t),this.data=this.content}}class Pe extends ue{version;flags;constructor(e,t){super(e,t);const i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}}class Ii extends Pe{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 i=0;i<this.referenceCount;i++){let r=this.readUint32();const n=r>>>31,o=r<<1>>>1,c=this.readUint32();r=this.readUint32();const u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:c,SAPType:u,SAPDeltaTime:l})}}}class Gs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class qs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var Fe;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(Fe||(Fe={}));class zs extends Pe{stereoMode;constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=Fe.MONOSCOPIC;break;case 1:this.stereoMode=Fe.TOP_BOTTOM;break;case 2:this.stereoMode=Fe.LEFT_RIGHT;break;case 3:this.stereoMode=Fe.STEREO_CUSTOM;break;case 4:this.stereoMode=Fe.RIGHT_LEFT;break}this.cursor+=1}}class Ws extends Pe{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Qs extends Pe{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Js extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Xs extends Pe{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e,t){super(e,t),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 Ks extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Zs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class ea extends Pe{sequenceNumber;constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class ta extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class ia extends Pe{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e,t){super(e,t),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 sa extends Pe{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class aa extends Pe{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e,t){super(e,t),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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())}}var G;(function(a){a.FtypBox="ftyp",a.MoovBox="moov",a.MoofBox="moof",a.MdatBox="mdat",a.SidxBox="sidx",a.TrakBox="trak",a.MdiaBox="mdia",a.MfhdBox="mfhd",a.TkhdBox="tkhd",a.TrafBox="traf",a.TfhdBox="tfhd",a.TfdtBox="tfdt",a.TrunBox="trun",a.MinfBox="minf",a.Sv3dBox="sv3d",a.St3dBox="st3d",a.PrhdBox="prhd",a.ProjBox="proj",a.EquiBox="equi",a.UnknownBox="unknown"})(G||(G={}));const ra={[G.FtypBox]:Us,[G.MoovBox]:Hs,[G.MoofBox]:js,[G.MdatBox]:Ys,[G.SidxBox]:Ii,[G.TrakBox]:Gs,[G.MdiaBox]:Js,[G.MfhdBox]:ea,[G.TkhdBox]:Xs,[G.TrafBox]:ta,[G.TfhdBox]:ia,[G.TfdtBox]:sa,[G.TrunBox]:aa,[G.MinfBox]:Ks,[G.Sv3dBox]:qs,[G.St3dBox]:zs,[G.PrhdBox]:Ws,[G.ProjBox]:Zs,[G.EquiBox]:Qs,[G.UnknownBox]:Ni};class Oe{options;constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let i=this.options.offset;for(;i<e.byteLength;){const n=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),o=this.createBox(n,new DataView(e.buffer,e.byteOffset+i));if(t.push(o),!o.size)break;i+=o.size}return t}createBox(e,t){const i=ra[e];return i?new i(t,new Oe):new Ni(t,new Oe)}}class Wt{index;constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]=this.index[t.type]||[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const na=new TextDecoder("ascii"),oa=a=>na.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ca=a=>{const e=new Ii(a,new Oe);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.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:D.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,c})},la=a=>{const t=new Oe().parse(a),i=new Wt(t),r=i.findAll("mdat"),n=i.findAll("moof");if(!(r.length&&n.length))return null;const o=n[0],c=r[r.length-1],u=o.source.byteOffset,d=c.source.byteOffset-o.source.byteOffset+c.size;return new DataView(a.buffer,u,d)},ua=(a,e)=>{const i=new Oe().parse(a),n=new Wt(i).findAll("traf"),o=n[n.length-1].children.find(h=>h.type==="tfhd"),c=n[n.length-1].children.find(h=>h.type==="tfdt"),u=n[n.length-1].children.find(h=>h.type==="trun");let l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((h,f)=>h+f,0):l=o.defaultSampleDuration*u.sampleCount,(Number(c.baseMediaDecodeTime)+l)/e*1e3},da=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:kt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Oe().parse(a),r=new Wt(i);if(r.find("sv3d")){e.is3dVideo=!0;const o=r.find("st3d");o&&(e.stereoMode=o.stereoMode);const c=r.find("prhd");c&&(e.projectionData.pose.yaw=c.poseYawDegrees,e.projectionData.pose.pitch=c.posePitchDegrees,e.projectionData.pose.roll=c.poseRollDegrees);const u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ha={validateData:oa,parseInit:da,getIndexRange:()=>{},parseSegments:ca,parseFeedableSegmentChunk:la,getSegmentEndTime:ua};var S;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(S||(S={}));var v;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.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}},Bi=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=At(a,t),r=i in oi,n=r?oi[i].type:v.Binary,o=a.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(a.buffer,a.byteOffset+t+1,c-1),l=o&255>>c,d=At(u),h=l*2**((c-1)*8)+d,f=t+c;let p;return f+h>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},At=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Te=(a,e)=>{switch(e){case v.SignedInteger:return a.getInt8(0);case v.UnsignedInteger:return At(a);case v.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case v.String:return new TextDecoder("ascii").decode(a);case v.UTF8:return new TextDecoder("utf-8").decode(a);case v.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case v.Master:return a;case v.Binary:return a;default:s.assertNever(e)}},et=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),r=Bi(i);if(!e(r))return;r.type===v.Master&&et(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},fa=a=>{if(a.getUint32(0)!==S.EBML)return!1;let e,t,i;const r=Bi(a);return et(r.value,({tag:n,type:o,value:c})=>(n===S.EBMLReadVersion?e=Te(c,o):n===S.DocType?t=Te(c,o):n===S.DocTypeReadVersion&&(i=Te(c,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Mi=[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],pa=[S.Timestamp,S.SilentTracks,S.SilentTrackNumber,S.Position,S.PrevSize,S.SimpleBlock,S.BlockGroup,S.EncryptedBlock],ma=a=>{let e,t,i,r,n=!1,o=!1,c=!1,u,l,d=!1;const h=0;return et(a,({tag:f,type:p,value:m,valueSize:T})=>{if(f===S.SeekID){const b=Te(m,p);l=At(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=Te(m,p):f===S.Duration?r=Te(m,p):f===S.SeekPosition&&l===S.Cues?u=Te(m,p):f===S.Tracks?et(m,({tag:b,type:y,value:C})=>b===S.ProjectionType?(d=Te(C,y)===1,!1):!0):n&&o&&Mi.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(r,"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(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:h,projectionType:kt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Sa=a=>{if(s.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ba=(a,e)=>{let t=!1,i=!1;const r=c=>s.isNonNullable(c.time)&&s.isNonNullable(c.position),n=[];let o;return et(a,({tag:c,type:u,value:l})=>{switch(c){case S.Cues:t=!0;break;case S.CuePoint:o&&r(o)&&n.push(o),o={};break;case S.CueTime:o&&(o.time=Te(l,u));break;case S.CueTrackPositions:break;case S.CueClusterPosition:o&&(o.position=Te(l,u));break;default:t&&Mi.includes(c)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((c,u)=>{const{time:l,position:d}=c,h=n[u+1];return{status:D.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}}})},ga=a=>{let e=0,t=!1;try{et(a,i=>i.tag===S.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):pa.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[S.SimpleBlock,S.BlockGroup,S.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},ya={validateData:fa,parseInit:ma,getIndexRange:Sa,parseSegments:ba,parseFeedableSegmentChunk:ga},va=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)},ci=a=>{if(!a.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(a),r=i?.[1]==="-"?-1:1,n={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Qe=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%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},Ta=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),r={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(Et.WEBM_AS_IN_FFMPEG)||C.includes(Et.WEBM_AS_IN_SPEC)?Ze.WEBM:Ze.MP4;for(const g of u){const E=g.getAttribute("mimeType"),F=g.getAttribute("codecs"),B=g.getAttribute("contentType")??E?.split("/")[0],R=g.getAttribute("profiles")?.split(",")??[],V=g.querySelectorAll("Representation"),k=g.querySelector("SegmentTemplate");if(B===Z.TEXT){for(const w of V){const N=w.getAttribute("id")||"",W=g.getAttribute("lang"),K=g.getAttribute("label"),de=w.querySelector("BaseURL")?.textContent?.trim()??"",$=new URL(de||c,e).toString(),_=N.includes("_auto");r[Z.TEXT].push({id:N,lang:W,label:K,isAuto:_,kind:Z.TEXT,url:$})}continue}for(const w of V){const N=w.getAttribute("mimeType")??E,W=w.getAttribute("codecs")??F??"",K=w.getAttribute("contentType")??N?.split("/")[0]??B,de=g.getAttribute("profiles")?.split(",")??[],$=parseInt(w.getAttribute("width")??"",10),_=parseInt(w.getAttribute("height")??"",10),Q=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,J=w.getAttribute("frameRate")??"",se=w.getAttribute("quality")??void 0,Ce=J?va(J):void 0,Lt=w.getAttribute("id")??(y++).toString(10),pt=K==="video"?`${_}p`:K==="audio"?`${Q}Kbps`:W,O=`${Lt}@${pt}`,ae=w.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(ae||c,e).toString(),he=[...C,...R,...de];let Ae;const it=w.querySelector("SegmentBase"),ne=w.querySelector("SegmentTemplate")??k;if(it){const fe=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Se,xt]=fe.split("-").map(qe=>parseInt(qe,10)),Le={from:Se,to:xt},st=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[Rt,mt]=st?st.split("-").map(qe=>parseInt(qe,10)):[],at=st?{from:Rt,to:mt}:void 0;Ae={type:le.BYTE_RANGE,url:re,initRange:Le,indexRange:at}}else if(ne){const fe={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},Se=parseInt(ne.getAttribute("timescale")??"",10),xt=ne.getAttribute("initialization")??"",Le=ne.getAttribute("media"),st=parseInt(ne.getAttribute("startNumber")??"",10)??1,Rt=Qe(xt,fe);if(!Le)throw new ReferenceError("No media attribute in SegmentTemplate");const mt=ne.querySelectorAll("SegmentTimeline S")??[],at=[];let qe=0,Nt="",It=0;if(mt.length){let St=st,pe=0;for(const ze of mt){const be=parseInt(ze.getAttribute("d")??"",10),Ie=parseInt(ze.getAttribute("r")??"",10)||0,bt=parseInt(ze.getAttribute("t")??"",10);pe=Number.isFinite(bt)?bt:pe;const Bt=be/Se*1e3,Yi=pe/Se*1e3;for(let gt=0;gt<Ie+1;gt++){const Gi=Qe(Le,{...fe,segmentNumber:St.toString(10),segmentTime:(pe+gt*be).toString(10)}),Xt=(Yi??0)+gt*Bt,qi=Xt+Bt;St++,at.push({time:{from:Xt,to:qi},url:Gi})}pe+=(Ie+1)*be,qe+=(Ie+1)*Bt}It=pe/Se*1e3,Nt=Qe(Le,{...fe,segmentNumber:St.toString(10),segmentTime:pe.toString(10)})}else if(s.isNonNullable(f)){const pe=parseInt(ne.getAttribute("duration")??"",10)/Se*1e3,ze=Math.ceil(f/pe);let be=0;for(let Ie=1;Ie<ze;Ie++){const bt=Qe(Le,{...fe,segmentNumber:Ie.toString(10),segmentTime:be.toString(10)});at.push({time:{from:be,to:be+pe},url:bt}),be+=pe}It=be,Nt=Qe(Le,{...fe,segmentNumber:ze.toString(10),segmentTime:be.toString(10)})}const ji={time:{from:It,to:1/0},url:Nt};Ae={type:le.TEMPLATE,baseUrl:re,segmentTemplateUrl:Le,initUrl:Rt,totalSegmentsDurationMs:qe,segments:at,nextSegmentBeyondManifest:ji,timescale:Se}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!K||!N)continue;const De={video:Z.VIDEO,audio:Z.AUDIO,text:Z.TEXT}[K];De&&r[De].push({id:O,kind:De,segmentReference:Ae,profiles:he,duration:f,bitrate:Q,mime:N,codecs:W,width:$,height:_,fps:Ce,quality:se})}}return{dynamic:l,liveAvailabilityStartTime:h,duration:f,container:P,representations:r}},Ea=({id:a,width:e,height:t,bitrate:i,fps:r,quality:n})=>{const o=(n?Pt(n):void 0)??s.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},ka=({id:a,bitrate:e})=>({id:a,bitrate:e}),Aa=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},wa=({id:a,lang:e,label:t,url:i,isAuto:r})=>({id:a,url:i,isAuto:r,type:"internal",language:e,label:t}),li=a=>"url"in a,We=a=>a.type===le.TEMPLATE,Ut=a=>a instanceof DOMException&&(a.name==="AbortError"||a.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 Ke;destroyAbortController=new Ke;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,r,{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 Ze.MP4:this.containerParser=ha;break;case Ze.WEBM:this.containerParser=ya;break;default:s.assertNever(i)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.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 Os(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),r=this.segments.get(t.id),n=this.parsedInitData.get(t.id);s.assertNonNullable(i,"No init buffer for starting representation"),s.assertNonNullable(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,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),r=this.initData.get(e);if(s.isNullable(r)||s.isNullable(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),s.assertNonNullable(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);const n=this.getCurrentPosition();s.isNonNullable(n)&&(this.isLive||(i.forEach(o=>o.status=D.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 Ke,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 r=i.find(l=>e>=l.time.from&&e<l.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=ct(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ni(this.sourceBuffer.buffered)>=this.bufferLimit){const l=ct(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&&r)if(c.includes(r))l="high";else{const d=c.at(0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(c,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===D.FED&&!c.length&&ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=i.at(-1);u&&u.status===D.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=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+r}),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,r=[];let n=0,o=t.length-1;do r.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()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(r=>r.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||!We(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 r=this.segments.get(t);s.assertNonNullable(r,"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(r,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||!We(t.segmentReference))return;const i=t.segmentReference.segments.map(c=>({...c,status:D.NONE,size:void 0})),r=this.segments.get(t.id)??[],n=r.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,[...r,...c])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!We(i))return;const r=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=Qe(i.segmentTemplateUrl,{segmentTime:r}),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:D.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(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=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===D.NONE||h===D.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!Ot(this.sourceBuffer.buffered,i))&&b&&C});if(r===-1)return[];if(t!==le.BYTE_RANGE)return e.slice(r,r+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=r;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===D.NONE||f.status===D.PARTIALLY_EJECTED)u.push(f);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===le.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=D.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);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;r.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,c),r.segment.status=D.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ut(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=D.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,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:r,onProgress:c,signal:o,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ut(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:r,signal:n,onProgress:(u,l)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:l,signal:n,onSegmentAppendFailed:o,globalFrom:r?r.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(!We(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 r=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:r,signal:n,onProgress:l,onProgressTasks:c}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,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){r();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=D.PARTIALLY_FED,c.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),c.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,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===le.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<r,C=b<=r;if(h.status===D.DOWNLOADING&&y&&C){h.status=D.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,r-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=D.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=D.FED,li(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const r of this.segments.get(i.id)??[])r.status===D.FED&&r.time.from===e.segment.time.from&&r.time.to===e.segment.time.to&&(r.status=D.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===D.PARTIALLY_FED||e.status===D.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=D.NONE),e.status=D.PARTIALLY_EJECTED):e.status=D.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[r,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=r)}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 r=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,r)).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&&We(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 r=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;r+=d};for(const l of this.segments.values())for(const d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;d.status===D.FED&&u(d)}if(c=isFinite(n)&&isFinite(o),!c){r=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)||r>t)break;d.status===D.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===D.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){r=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===D.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 r={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){r=void 0;break}c>i.time.from&&c<i.time.to&&(r.from=c),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}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 r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==D.FED&&n!==D.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),c=Math.ceil(r.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||this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status=D.PARTIALLY_EJECTED:r.status=D.NONE)}}}var Ht=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},$a=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?exports.HttpConnectionType.HTTP1:e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}},Xe;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(Xe||(Xe={}));class Pa{throughputEstimator;requestQuic;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);abortAllController=new Ke;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}=$a(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=s.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ht(t));const i=yield dt(t,{signal:this.abortAllController.signal}).catch(rt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=s.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Xe.HEADER:Xe.PARAM,range:i,onProgress:r,priority:n="auto",signal:o,measureThroughput:c=!0,isLowLatency:u=!1}={}){let l=e;const d=new Headers;if(i)switch(t){case Xe.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case Xe.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=Ht(l));let h=this.abortAllController.signal,f;if(o){const R=new Ke;if(f=s.merge(s.fromEvent(this.abortAllController.signal,"abort"),s.fromEvent(o,"abort")).subscribe(()=>{try{R.abort()}catch(V){rt(V)}}),this.abortAllController.signal.aborted||o.aborted)try{R.abort()}catch(V){rt(V)}h=R.signal}const p=s.now(),m=yield dt(l,{priority:n,headers:d,signal:h}).catch(rt),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),!r&&!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 F=R=>{f?.unsubscribe(),E=!0,rt(R)},B=s.abortable(h,async function*({done:R,value:V}){if(P===0&&this.lastRequestFirstBytes$.next(s.now()-p),h.aborted){f?.unsubscribe();return}if(!R&&V){const k=new Uint8Array(g.length+V.length);k.set(g),k.set(V,g.length),g=k,P+=V.byteLength,r?.(new DataView(g.buffer),P),yield C?.read().then(B,F)}}.bind(this));return yield C?.read().then(B,F),f?.unsubscribe(),E?null:g.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:r}=e;switch(r){case le.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case le.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:s.assertNever(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==le.BYTE_RANGE)return null;const{from:r,to:n}=e.initRange;let o=r,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,r),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,r-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!==le.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(o=>({...o,status:D.NONE,size:void 0})),dataView:new DataView(r)}:null}.bind(this))}const rt=a=>{if(!Ut(a))throw a},Je=1e3,wt=(a,e,t)=>t*e+(1-t)*a,Vi=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Ca=(a,e,t,i)=>{let r=0,n=t;const o=Vi(a,e),c=e<i?e:i;for(let u=0;u<c;u++)a[n]>o?r++:r--,n=(a.length+n-1)%a.length;return Math.abs(r)===c};class Qt{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 ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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 r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;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 Da extends Qt{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 La extends Qt{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Vi(this.pastMeasures,this.takenMeasures);this.emaSmoothed=wt(this.emaSmoothed,e,this.params.emaAlpha);const i=Ca(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class xa extends Qt{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 jt{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Da({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new La({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 xa({initial:e,label:"liveEdgeDelay",...t})}}const Ra=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Be=()=>window.ManagedMediaSource||window.MediaSource,_i=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Na=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Ia=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,di=["timeupdate","progress","play","seeked","stalled","waiting"];var ce;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(ce||(ce={}));let Ba=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new s.Subscription;representationSubscription=new s.Subscription;fetcher;state$=new z(ce.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;timeInWaiting=0;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new s.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;stallWatchdogSubscription;destroyController=new Ke;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Pa({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=jt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=s.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=me(t,i,X.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ce.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(ce.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(r=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:s.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:r})});if(!e)return null;let t;try{t=Ta(e??"",this.manifestUrlString)}catch(r){this.error$.next({id:"ManifestParsing",category:s.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:r})}if(!t)return null;const i=({kind:r,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&Be()?.isTypeSupported?.(`${n}; codecs="${o}"`)||r===Z.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(([r,n])=>[r,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.manifestUrlString=me(this.manifestUrlString,t,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,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(ce.REPRESENTATIOS_READY);const r=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?Ia():new MediaSource;const n=document.createElement("source");if(r(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),this.tuning.useManagedMediaSource&&_i())if(i){const p=document.createElement("source");r(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(Z.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,o),this.bufferManagers=[this.videoBufferManager],s.isNonNullable(t)&&(this.audioBufferManager=new ui(Z.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(Je).subscribe(p=>{if(this.element?.paused){const m=Zt(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=me(this.manifestUrlString,m+Je,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(s.merge(...di.filter(p=>p!=="waiting").map(p=>s.fromEvent(this.element,p))).pipe(s.map(p=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),s.filterChanged(),s.filter(p=>!!p),s.tap(p=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=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),Ra(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??b))-b}this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let p=0;this.representationSubscription.add(s.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(s.throttle(Je)).subscribe(async({liveLoadBufferLength:m,bufferLength:T})=>{if(s.assertNonNullable(this.element),this.isUpdatingLive)return;const b=this.element.playbackRate,y=Zt(this.manifestUrlString,X.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,F=this.isActiveLowLatency?T:m;let B=ye.None;if(this.isActiveLowLatency?B=ye.ActiveLowLatency:F<P+E&&F>=P?B=ye.LiveWithTargetOffset:y!==0&&F<P&&(B=ye.LiveForwardBuffering),isFinite(m)&&(p=m>p?m:p),B===ye.LiveForwardBuffering||B===ye.LiveWithTargetOffset){const R=p-(P+g),V=this.normolizeLiveOffset(Math.trunc(y+R/b)),k=Math.abs(V-y);let w;!m||k<=this.tuning.dashCmafLive.offsetCalculationError?w=y:V>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=V:w=0,this.manifestUrlString=me(this.manifestUrlString,w,X.DASH_CMAF_OFFSET_P)}B!==ye.None&&B!==ye.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(ce.REPRESENTATIOS_READY)}.bind(this));initBuffer(){s.assertNonNullable(this.element),this.state$.setState(ce.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);const e=()=>{if(this.element){if(this.timeInWaiting+=Je,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=s.interval(Je).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:s.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{[Z.VIDEO]:this.videoBufferManager,[Z.AUDIO]:this.audioBufferManager,[Z.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(ce.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}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=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const n of this.bufferManagers)for(const o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-r<=t&&o.to+r>t&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){const n=Math.max(...i)+10;n===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=n/1e3}}};class Ma{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Va{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 r=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:r,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 r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>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 _a=`#define GLSLIFY 1
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;}`,Fa=`#ifdef GL_ES
37
+ `}),k}return l?.recordSwitch(R),R};var ke=a=>new URL(a).hostname;const si=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var Ge=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!si(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return si(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function te(){return s.now()}function Pi(a){return te()-a}function ai(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=o=>i.test(o);return{resolve:(o,c,u=!1)=>{r(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 ks(a,e,t){const i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Et(a,e,t,i){const r=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=Pi(d);let W;if(N<T){W=T-N,setTimeout(b,W);return}T*=2,T>m&&(T=m),o&&o.abort(),o=new r,F()};const y=N=>(n=N,w),C=N=>(h=N,w),P=()=>(p="json",w),g=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,h&&h(),t&&t()}},E=N=>(f=N,w),F=()=>{d=te(),o=new r,o.open("get",a);let N=0,W,K=0;const de=()=>(s.assertNonNullable(d),Math.max(d,Math.max(W||0,K||0)));if(n&&o.addEventListener("progress",$=>{const _=te();n.updateChunk&&$.loaded>N&&(n.updateChunk(de(),$.loaded-N),N=$.loaded,W=_)}),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.response.byteLength-N;_&&n.updateChunk&&n.updateChunk(de(),_)}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&&(K=te(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),w},w={withBitrateReporting:y,withParallel:E,withJSONResponse:P,withRetryCount:N=>(l=N,w),withRetryInterval:(N,W)=>(s.isNonNullable(N)&&(T=N),s.isNonNullable(W)&&(m=W),w),withTimeout:N=>(c=N,w),withFinally:C,send:F,abort:()=>{o&&(o.abort(),o=void 0),u=!0,h&&h()}};return w}const As=100,ws=2e3,$s=500;let Ps=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-$s;if(t-e>ws){let i=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,r+=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;r+=u,n.start=t,n.bytes-=u}}}if(r>0&&i>0){const n=r*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(r)}/${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>As&&(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 Cs{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,r,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,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=te(),r=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=te()-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=Et(t,n,()=>r("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=te()}_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=te();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,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=r,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=r,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 Tt=1e4,Vt=3,Ds=6e4,Ls=10,xs=1,Rs=500;class Ns{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 Ps(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ai(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ai(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,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)?(!r||n.bitrate>r.bitrate)&&(r=n):(!i||i.bitrate>n.bitrate)&&(i=n));return r||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:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{ks(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 Cs(Vt,Tt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=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,F)=>{u&&u.abort(),u=Et(this.urlResolver.resolve(g,!1),E,F,()=>this._retryCallback()).withTimeout(Tt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Vt).withFinally(()=>{u=null}).send()},p=(g,E,F)=>{s.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),E,F,()=>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 F=te()-1e4;let B=0;for(let V=0;V<this.bufferStates.length;V++){const k=this.bufferStates[V];g=Math.min(g,k.buf),k.ts<F&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${g} drop=${B} jitter=${this.sourceJitter}`);let R=g-xs;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 F=()=>E&&E.start?E.start.length:0,B=$=>E.start[$]/1e3,R=$=>E.dur[$]/1e3,V=$=>E.fragIndex+$,k=($,_)=>({chunkIdx:V($),startTS:B($),dur:R($),discontinuity:_}),w=()=>{let $=0;if(E&&E.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=_;this.sourceJitter>1&&(J+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(J-=E.dur[se],!(J<=0));--se);$=Math.min(se,E.dur.length-1-Q),$=Math.max($,0)}return k($,!0)},N=$=>{const _=F();if(!(_<=0)){if(s.isNonNullable($)){for(let Q=0;Q<_;Q++)if(B(Q)>$)return k(Q)}return w()}},W=$=>{const _=F(),Q=$?$.chunkIdx+1:0,J=Q-E.fragIndex;if(!(_<=0)){if(!$||J<0||J-_>Ls)return t(`Resync: offset=${J} bChunks=${_} chunk=`+JSON.stringify($)),w();if(!(J>=_))return k(Q-E.fragIndex,!1)}},K=($,_,Q)=>{l&&l.abort(),l=Et(this.urlResolver.resolve($,!0,this.lowLatency),_,Q,()=>this._retryCallback()).withTimeout(Tt).withRetryCount(Vt).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,_)=>{K(g,Q=>{if(!h())return;E=Q;const J=!!E.lowLatency;J!==this.lowLatency&&T(J);let se=0;for(let Ce=0;Ce<E.dur.length;++Ce)se+=E.dur[Ce];se>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(N(_))},()=>this._handleNetworkError())},nextChunk:W}},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:F}=this.params;let B=y(e.jidxUrl),R,V,k,w,N=0,W,K,de;const $=()=>{W&&(clearTimeout(W),W=void 0);const O=Math.max(Rs,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=N+O,re=te(),he=Math.min(1e4,ae-re);N=re;const Ae=()=>{l||h()&&B.seek(()=>{h()&&(N=te(),_(),$())})};he>0?W=window.setTimeout(()=>{this.paused?$():Ae()},he):Ae()},_=()=>{let O;for(;O=B.nextChunk(w);)w=O,xt(O);const ae=B.nextChunk(k);if(ae){if(k&&ae.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?$():(C(),this._initPlayerWith(e));return}Ce(ae)}else $()},Q=(O,ae)=>{if(!h()||!this.sourceBuffer)return;let re,he,Ae;const st=ne=>{window.setTimeout(()=>{h()&&Q(O,ae)},ne)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),st(100);else{const ne=te(),De=E.currentTime;!this.paused&&E.buffered.length>1&&K===De&&ne-de>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),K!==De&&(K=De,de=ne);const fe=this._getBufferSizeSec();if(fe>30)F(`Buffered ${fe} seconds; delaying appendBuffer`),st(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:ne,buf:fe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(Se){if(Se.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Ae=this.sourceBuffer.buffered.length,Ae!==0&&(re=this.sourceBuffer.buffered.start(0),he=De,he-re>4&&this.sourceBuffer.remove(re,he-3)),st(1e3);else throw Se}}},J=()=>{V&&R&&(F([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(k)]),Q(V,function(){V=null,_()}))},se=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),Ce=O=>{h()&&p(se(O),(ae,re)=>{if(h()){if(re/=1e3,V=ae,k=O,o=O.startTS,re){const he=Math.min(10,O.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}J()}},()=>this._handleNetworkError())},xt=O=>{h()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(O),!1)))},mt=O=>{h()&&(e.cachedHeader=O,Q(O,()=>{R=!0,J()}))};n=!0,B.seek(O=>{if(h()){if(N=te(),!O){$();return}w=O,!s.isNullable(g)||O.startTS>g?Ce(O):(k=O,_())}},g),e.cachedHeader?mt(e.cachedHeader):f(e.headerUrl,mt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s.isNonNullable(r)&&(r+=.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(r),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=te();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&&Pi(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=te();h<c&&(o=f),c=h}}}_fetchManifest(e,t,i){this.manifestRequest=Et(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Tt).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;Ge(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,n=o=>{const c=[];return o?.length?(o.forEach((u,l)=>{u.video&&r.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))},Ds))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Ci{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 r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),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,r=t-this.prevDroppedVideoFrames,n=1-(i-r)/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],[r])=>s.isLower(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Ut=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,it=(a,e)=>new s.Observable(t=>{if(!window.IntersectionObserver)return;const i={root:null},r=new IntersectionObserver((o,c)=>{o.forEach(u=>t.next(u.isIntersecting||Ut()))},{...i,...e});r.observe(a);const n=s.fromEvent(document,"visibilitychange").pipe(s.map(o=>!document.hidden||Ut())).subscribe(o=>t.next(o));return()=>{r.unobserve(a),n.unsubscribe}});var x;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(x||(x={}));const Is=[x.PAUSED,x.PLAYING,x.READY],Bs=[x.PAUSED,x.PLAYING,x.READY];class Ms{subscription=new s.Subscription;video;videoState=new z(x.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new Ne;droppedFramesManager=new Ci;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=r=>{e.output.error$.next({id:"DashLiveProvider",category:s.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=Ue(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(ke(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=Ye(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(r=>r.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(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(s.combine({zeroTime:this.zeroTime$.pipe(s.filter(s.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(pt(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(tt(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(it(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const n=r&&s.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.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(r.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),He(this.video)}createLiveDashPlayer(){const e=new Ns({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(),r=!i&&s.isNonNullable(t)?t:Dt(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=r?.id,o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(o||n!==c)&&this.setVideoTrack(r),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(),r=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(me(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}_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 r of t){const n=r.name??r.index.toString(10),o=Ct(r.name)??s.videoSizeToQuality(r.video),c=r.bitrate/1e3,u={...r.video};if(!o)continue;const l={id:n,quality:o,bitrate:c,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),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:r})=>r===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(),r=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(Bs.includes(e)&&(o||c)){this.prepare();return}if(r?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&Is.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(me(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const u=r?.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(me(this.params.source.url,u))}return;default:return s.assertNever(e)}}}var Z;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Z||(Z={}));var ye;(function(a){a[a.ActiveLowLatency=0]="ActiveLowLatency",a[a.LiveWithTargetOffset=1]="LiveWithTargetOffset",a[a.LiveForwardBuffering=2]="LiveForwardBuffering",a[a.None=3]="None"})(ye||(ye={}));var kt;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(kt||(kt={}));var le;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(le||(le={}));var D;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(D||(D={}));var Ze;(function(a){a.MP4="mp4",a.WEBM="webm"})(Ze||(Ze={}));var At;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(At||(At={}));var Y;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));var lt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const r=a.start(i)*1e3,n=a.end(i)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};class ri{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[r];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 Di extends ri{constructor(){super(),this.listeners||ri.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Li=class{constructor(){Object.defineProperty(this,"signal",{value:new Di,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&&(Li.prototype[Symbol.toStringTag]="AbortController",Di.prototype[Symbol.toStringTag]="AbortSignal");function xi(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Vs(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!xi({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(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 Lt=xi({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ri=Lt?Vs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Lt?Ri.fetch:window.fetch;Lt?Ri.Request:window.Request;const Ke=Lt?Li:window.AbortController;var Ht=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const _s=(a,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Fs=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ni=Fs?_s:window.requestIdleCallback,Os=16;let Ni=!1;try{Ni=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Os}catch(a){console.error(a)}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 r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Ni&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:s.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:s.assertNever(t)}}}var oi=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class ue{source;boxParser;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e,t){this.source=e,this.boxParser=t,this.children=[];const i=this.readUint32();this.size32=i<=e.buffer.byteLength?i: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[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 Ii extends ue{}class Hs extends ue{majorBrand;minorVersion;compatibleBrands;constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){const r=this.readString(4);this.compatibleBrands.push(r),i-=4}}}class js extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ys extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Gs extends ue{data;constructor(e,t){super(e,t),this.data=this.content}}class Pe extends ue{version;flags;constructor(e,t){super(e,t);const i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}}class Bi extends Pe{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 i=0;i<this.referenceCount;i++){let r=this.readUint32();const n=r>>>31,o=r<<1>>>1,c=this.readUint32();r=this.readUint32();const u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:c,SAPType:u,SAPDeltaTime:l})}}}class qs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class zs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var Fe;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(Fe||(Fe={}));class Ws extends Pe{stereoMode;constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=Fe.MONOSCOPIC;break;case 1:this.stereoMode=Fe.TOP_BOTTOM;break;case 2:this.stereoMode=Fe.LEFT_RIGHT;break;case 3:this.stereoMode=Fe.STEREO_CUSTOM;break;case 4:this.stereoMode=Fe.RIGHT_LEFT;break}this.cursor+=1}}class Qs extends Pe{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Js extends Pe{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Xs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ks extends Pe{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e,t){super(e,t),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 Zs extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class ea extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class ta extends Pe{sequenceNumber;constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class ia extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class sa extends Pe{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e,t){super(e,t),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 aa extends Pe{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class ra extends Pe{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e,t){super(e,t),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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())}}var G;(function(a){a.FtypBox="ftyp",a.MoovBox="moov",a.MoofBox="moof",a.MdatBox="mdat",a.SidxBox="sidx",a.TrakBox="trak",a.MdiaBox="mdia",a.MfhdBox="mfhd",a.TkhdBox="tkhd",a.TrafBox="traf",a.TfhdBox="tfhd",a.TfdtBox="tfdt",a.TrunBox="trun",a.MinfBox="minf",a.Sv3dBox="sv3d",a.St3dBox="st3d",a.PrhdBox="prhd",a.ProjBox="proj",a.EquiBox="equi",a.UnknownBox="unknown"})(G||(G={}));const na={[G.FtypBox]:Hs,[G.MoovBox]:js,[G.MoofBox]:Ys,[G.MdatBox]:Gs,[G.SidxBox]:Bi,[G.TrakBox]:qs,[G.MdiaBox]:Xs,[G.MfhdBox]:ta,[G.TkhdBox]:Ks,[G.TrafBox]:ia,[G.TfhdBox]:sa,[G.TfdtBox]:aa,[G.TrunBox]:ra,[G.MinfBox]:Zs,[G.Sv3dBox]:zs,[G.St3dBox]:Ws,[G.PrhdBox]:Qs,[G.ProjBox]:ea,[G.EquiBox]:Js,[G.UnknownBox]:Ii};class Oe{options;constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let i=this.options.offset;for(;i<e.byteLength;){const n=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),o=this.createBox(n,new DataView(e.buffer,e.byteOffset+i));if(t.push(o),!o.size)break;i+=o.size}return t}createBox(e,t){const i=na[e];return i?new i(t,new Oe):new Ii(t,new Oe)}}class Qt{index;constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]=this.index[t.type]||[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const oa=new TextDecoder("ascii"),ca=a=>oa.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",la=a=>{const e=new Bi(a,new Oe);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.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:D.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,c})},ua=a=>{const t=new Oe().parse(a),i=new Qt(t),r=i.findAll("mdat"),n=i.findAll("moof");if(!(r.length&&n.length))return null;const o=n[0],c=r[r.length-1],u=o.source.byteOffset,d=c.source.byteOffset-o.source.byteOffset+c.size;return new DataView(a.buffer,u,d)},da=(a,e)=>{const i=new Oe().parse(a),n=new Qt(i).findAll("traf"),o=n[n.length-1].children.find(h=>h.type==="tfhd"),c=n[n.length-1].children.find(h=>h.type==="tfdt"),u=n[n.length-1].children.find(h=>h.type==="trun");let l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((h,f)=>h+f,0):l=o.defaultSampleDuration*u.sampleCount,(Number(c.baseMediaDecodeTime)+l)/e*1e3},ha=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:At.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Oe().parse(a),r=new Qt(i);if(r.find("sv3d")){e.is3dVideo=!0;const o=r.find("st3d");o&&(e.stereoMode=o.stereoMode);const c=r.find("prhd");c&&(e.projectionData.pose.yaw=c.poseYawDegrees,e.projectionData.pose.pitch=c.posePitchDegrees,e.projectionData.pose.roll=c.poseRollDegrees);const u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},fa={validateData:ca,parseInit:ha,getIndexRange:()=>{},parseSegments:la,parseFeedableSegmentChunk:ua,getSegmentEndTime:da};var S;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(S||(S={}));var v;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(v||(v={}));const ci={[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}},Mi=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=wt(a,t),r=i in ci,n=r?ci[i].type:v.Binary,o=a.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(a.buffer,a.byteOffset+t+1,c-1),l=o&255>>c,d=wt(u),h=l*2**((c-1)*8)+d,f=t+c;let p;return f+h>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},wt=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Te=(a,e)=>{switch(e){case v.SignedInteger:return a.getInt8(0);case v.UnsignedInteger:return wt(a);case v.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case v.String:return new TextDecoder("ascii").decode(a);case v.UTF8:return new TextDecoder("utf-8").decode(a);case v.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case v.Master:return a;case v.Binary:return a;default:s.assertNever(e)}},et=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),r=Mi(i);if(!e(r))return;r.type===v.Master&&et(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},pa=a=>{if(a.getUint32(0)!==S.EBML)return!1;let e,t,i;const r=Mi(a);return et(r.value,({tag:n,type:o,value:c})=>(n===S.EBMLReadVersion?e=Te(c,o):n===S.DocType?t=Te(c,o):n===S.DocTypeReadVersion&&(i=Te(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],ma=[S.Timestamp,S.SilentTracks,S.SilentTrackNumber,S.Position,S.PrevSize,S.SimpleBlock,S.BlockGroup,S.EncryptedBlock],Sa=a=>{let e,t,i,r,n=!1,o=!1,c=!1,u,l,d=!1;const h=0;return et(a,({tag:f,type:p,value:m,valueSize:T})=>{if(f===S.SeekID){const b=Te(m,p);l=wt(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=Te(m,p):f===S.Duration?r=Te(m,p):f===S.SeekPosition&&l===S.Cues?u=Te(m,p):f===S.Tracks?et(m,({tag:b,type:y,value:C})=>b===S.ProjectionType?(d=Te(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(r,"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(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:h,projectionType:At.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ba=a=>{if(s.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ga=(a,e)=>{let t=!1,i=!1;const r=c=>s.isNonNullable(c.time)&&s.isNonNullable(c.position),n=[];let o;return et(a,({tag:c,type:u,value:l})=>{switch(c){case S.Cues:t=!0;break;case S.CuePoint:o&&r(o)&&n.push(o),o={};break;case S.CueTime:o&&(o.time=Te(l,u));break;case S.CueTrackPositions:break;case S.CueClusterPosition:o&&(o.position=Te(l,u));break;default:t&&Vi.includes(c)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((c,u)=>{const{time:l,position:d}=c,h=n[u+1];return{status:D.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}}})},ya=a=>{let e=0,t=!1;try{et(a,i=>i.tag===S.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ma.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[S.SimpleBlock,S.BlockGroup,S.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},va={validateData:pa,parseInit:Sa,getIndexRange:ba,parseSegments:ga,parseFeedableSegmentChunk:ya},Ta=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)},li=a=>{if(!a.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(a),r=i?.[1]==="-"?-1:1,n={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Qe=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%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},Ea=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),r={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=li(p);else if(m){const g=li(m);s.isNonNullable(g)&&(f=g)}else b&&(f=parseInt(b,10));let y=0;const C=n.getAttribute("profiles")?.split(",")??[],P=C.includes(kt.WEBM_AS_IN_FFMPEG)||C.includes(kt.WEBM_AS_IN_SPEC)?Ze.WEBM:Ze.MP4;for(const g of u){const E=g.getAttribute("mimeType"),F=g.getAttribute("codecs"),B=g.getAttribute("contentType")??E?.split("/")[0],R=g.getAttribute("profiles")?.split(",")??[],V=g.querySelectorAll("Representation"),k=g.querySelector("SegmentTemplate");if(B===Z.TEXT){for(const w of V){const N=w.getAttribute("id")||"",W=g.getAttribute("lang"),K=g.getAttribute("label"),de=w.querySelector("BaseURL")?.textContent?.trim()??"",$=new URL(de||c,e).toString(),_=N.includes("_auto");r[Z.TEXT].push({id:N,lang:W,label:K,isAuto:_,kind:Z.TEXT,url:$})}continue}for(const w of V){const N=w.getAttribute("mimeType")??E,W=w.getAttribute("codecs")??F??"",K=w.getAttribute("contentType")??N?.split("/")[0]??B,de=g.getAttribute("profiles")?.split(",")??[],$=parseInt(w.getAttribute("width")??"",10),_=parseInt(w.getAttribute("height")??"",10),Q=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,J=w.getAttribute("frameRate")??"",se=w.getAttribute("quality")??void 0,Ce=J?Ta(J):void 0,xt=w.getAttribute("id")??(y++).toString(10),mt=K==="video"?`${_}p`:K==="audio"?`${Q}Kbps`:W,O=`${xt}@${mt}`,ae=w.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(ae||c,e).toString(),he=[...C,...R,...de];let Ae;const st=w.querySelector("SegmentBase"),ne=w.querySelector("SegmentTemplate")??k;if(st){const fe=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Se,Rt]=fe.split("-").map(qe=>parseInt(qe,10)),Le={from:Se,to:Rt},at=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[Nt,St]=at?at.split("-").map(qe=>parseInt(qe,10)):[],rt=at?{from:Nt,to:St}:void 0;Ae={type:le.BYTE_RANGE,url:re,initRange:Le,indexRange:rt}}else if(ne){const fe={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},Se=parseInt(ne.getAttribute("timescale")??"",10),Rt=ne.getAttribute("initialization")??"",Le=ne.getAttribute("media"),at=parseInt(ne.getAttribute("startNumber")??"",10)??1,Nt=Qe(Rt,fe);if(!Le)throw new ReferenceError("No media attribute in SegmentTemplate");const St=ne.querySelectorAll("SegmentTimeline S")??[],rt=[];let qe=0,It="",Bt=0;if(St.length){let bt=at,pe=0;for(const ze of St){const be=parseInt(ze.getAttribute("d")??"",10),Ie=parseInt(ze.getAttribute("r")??"",10)||0,gt=parseInt(ze.getAttribute("t")??"",10);pe=Number.isFinite(gt)?gt:pe;const Mt=be/Se*1e3,Gi=pe/Se*1e3;for(let yt=0;yt<Ie+1;yt++){const qi=Qe(Le,{...fe,segmentNumber:bt.toString(10),segmentTime:(pe+yt*be).toString(10)}),Kt=(Gi??0)+yt*Mt,zi=Kt+Mt;bt++,rt.push({time:{from:Kt,to:zi},url:qi})}pe+=(Ie+1)*be,qe+=(Ie+1)*Mt}Bt=pe/Se*1e3,It=Qe(Le,{...fe,segmentNumber:bt.toString(10),segmentTime:pe.toString(10)})}else if(s.isNonNullable(f)){const pe=parseInt(ne.getAttribute("duration")??"",10)/Se*1e3,ze=Math.ceil(f/pe);let be=0;for(let Ie=1;Ie<ze;Ie++){const gt=Qe(Le,{...fe,segmentNumber:Ie.toString(10),segmentTime:be.toString(10)});rt.push({time:{from:be,to:be+pe},url:gt}),be+=pe}Bt=be,It=Qe(Le,{...fe,segmentNumber:ze.toString(10),segmentTime:be.toString(10)})}const Yi={time:{from:Bt,to:1/0},url:It};Ae={type:le.TEMPLATE,baseUrl:re,segmentTemplateUrl:Le,initUrl:Nt,totalSegmentsDurationMs:qe,segments:rt,nextSegmentBeyondManifest:Yi,timescale:Se}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!K||!N)continue;const De={video:Z.VIDEO,audio:Z.AUDIO,text:Z.TEXT}[K];De&&r[De].push({id:O,kind:De,segmentReference:Ae,profiles:he,duration:f,bitrate:Q,mime:N,codecs:W,width:$,height:_,fps:Ce,quality:se})}}return{dynamic:l,liveAvailabilityStartTime:h,duration:f,container:P,representations:r}},ka=({id:a,width:e,height:t,bitrate:i,fps:r,quality:n})=>{const o=(n?Ct(n):void 0)??s.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},Aa=({id:a,bitrate:e})=>({id:a,bitrate:e}),wa=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},$a=({id:a,lang:e,label:t,url:i,isAuto:r})=>({id:a,url:i,isAuto:r,type:"internal",language:e,label:t}),ui=a=>"url"in a,We=a=>a.type===le.TEMPLATE,jt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class di{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 Ke;destroyAbortController=new Ke;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,r,{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 Ze.MP4:this.containerParser=fa;break;case Ze.WEBM:this.containerParser=va;break;default:s.assertNever(i)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.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,oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=c,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),r=this.segments.get(t.id),n=this.parsedInitData.get(t.id);s.assertNonNullable(i,"No init buffer for starting representation"),s.assertNonNullable(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,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),r=this.initData.get(e);if(s.isNullable(r)||s.isNullable(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),s.assertNonNullable(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);const n=this.getCurrentPosition();s.isNonNullable(n)&&(this.isLive||(i.forEach(o=>o.status=D.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 Ke,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 r=i.find(l=>e>=l.time.from&&e<l.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=lt(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&oi(this.sourceBuffer.buffered)>=this.bufferLimit){const l=lt(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&&r)if(c.includes(r))l="high";else{const d=c.at(0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(c,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===D.FED&&!c.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=i.at(-1);u&&u.status===D.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=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+r}),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,r=[];let n=0,o=t.length-1;do r.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()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(r=>r.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||!We(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 r=this.segments.get(t);s.assertNonNullable(r,"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(r,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||!We(t.segmentReference))return;const i=t.segmentReference.segments.map(c=>({...c,status:D.NONE,size:void 0})),r=this.segments.get(t.id)??[],n=r.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,[...r,...c])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!We(i))return;const r=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=Qe(i.segmentTemplateUrl,{segmentTime:r}),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:D.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(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=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===D.NONE||h===D.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!Ht(this.sourceBuffer.buffered,i))&&b&&C});if(r===-1)return[];if(t!==le.BYTE_RANGE)return e.slice(r,r+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=r;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===D.NONE||f.status===D.PARTIALLY_EJECTED)u.push(f);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===le.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=D.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);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;r.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,c),r.segment.status=D.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),jt(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=D.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,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:r,onProgress:c,signal:o,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),jt(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:r,signal:n,onProgress:(u,l)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:l,signal:n,onSegmentAppendFailed:o,globalFrom:r?r.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(!We(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 r=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:r,signal:n,onProgress:l,onProgressTasks:c}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,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){r();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=D.PARTIALLY_FED,c.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),c.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,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===le.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<r,C=b<=r;if(h.status===D.DOWNLOADING&&y&&C){h.status=D.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,r-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=D.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=D.FED,ui(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const r of this.segments.get(i.id)??[])r.status===D.FED&&r.time.from===e.segment.time.from&&r.time.to===e.segment.time.to&&(r.status=D.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===D.PARTIALLY_FED||e.status===D.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=D.NONE),e.status=D.PARTIALLY_EJECTED):e.status=D.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[r,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=ni(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=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,r)).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&&We(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 r=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=ui(l)?l.size??0:l.byte.to-l.byte.from;r+=d};for(const l of this.segments.values())for(const d of l){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;d.status===D.FED&&u(d)}if(c=isFinite(n)&&isFinite(o),!c){r=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)||r>t)break;d.status===D.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===D.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){r=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===D.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 r={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){r=void 0;break}c>i.time.from&&c<i.time.to&&(r.from=c),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ni(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:s.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(s.isNullable(this.sourceBuffer)||s.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==D.FED&&n!==D.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),c=Math.ceil(r.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||this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status=D.PARTIALLY_EJECTED:r.status=D.NONE)}}}var Yt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Pa=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?exports.HttpConnectionType.HTTP1:e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}},Xe;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(Xe||(Xe={}));class Ca{throughputEstimator;requestQuic;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);abortAllController=new Ke;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}=Pa(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=s.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Yt(t));const i=yield ht(t,{signal:this.abortAllController.signal}).catch(nt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=s.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Xe.HEADER:Xe.PARAM,range:i,onProgress:r,priority:n="auto",signal:o,measureThroughput:c=!0,isLowLatency:u=!1}={}){let l=e;const d=new Headers;if(i)switch(t){case Xe.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case Xe.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=Yt(l));let h=this.abortAllController.signal,f;if(o){const R=new Ke;if(f=s.merge(s.fromEvent(this.abortAllController.signal,"abort"),s.fromEvent(o,"abort")).subscribe(()=>{try{R.abort()}catch(V){nt(V)}}),this.abortAllController.signal.aborted||o.aborted)try{R.abort()}catch(V){nt(V)}h=R.signal}const p=s.now(),m=yield ht(l,{priority:n,headers:d,signal:h}).catch(nt),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),!r&&!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 F=R=>{f?.unsubscribe(),E=!0,nt(R)},B=s.abortable(h,async function*({done:R,value:V}){if(P===0&&this.lastRequestFirstBytes$.next(s.now()-p),h.aborted){f?.unsubscribe();return}if(!R&&V){const k=new Uint8Array(g.length+V.length);k.set(g),k.set(V,g.length),g=k,P+=V.byteLength,r?.(new DataView(g.buffer),P),yield C?.read().then(B,F)}}.bind(this));return yield C?.read().then(B,F),f?.unsubscribe(),E?null:g.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:r}=e;switch(r){case le.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case le.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:s.assertNever(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==le.BYTE_RANGE)return null;const{from:r,to:n}=e.initRange;let o=r,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,r),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,r-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!==le.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(o=>({...o,status:D.NONE,size:void 0})),dataView:new DataView(r)}:null}.bind(this))}const nt=a=>{if(!jt(a))throw a},Je=1e3,$t=(a,e,t)=>t*e+(1-t)*a,_i=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Da=(a,e,t,i)=>{let r=0,n=t;const o=_i(a,e),c=e<i?e:i;for(let u=0;u<c;u++)a[n]>o?r++:r--,n=(a.length+n-1)%a.length;return Math.abs(r)===c};class Jt{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 ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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 r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;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 La extends Jt{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class xa extends Jt{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=_i(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);const i=Da(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Ra extends Jt{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?$t(this.smoothed,e,this.params.emaAlpha):e}}class Gt{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new La({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new xa({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 Ra({initial:e,label:"liveEdgeDelay",...t})}}const Na=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Be=()=>window.ManagedMediaSource||window.MediaSource,Fi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Ia=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Ba=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,hi=["timeupdate","progress","play","seeked","stalled","waiting"];var ce;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(ce||(ce={}));let Ma=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new s.Subscription;representationSubscription=new s.Subscription;fetcher;state$=new z(ce.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;timeInWaiting=0;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new s.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;stallWatchdogSubscription;destroyController=new Ke;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ca({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=me(t,i,X.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ce.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(ce.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(r=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:s.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:r})});if(!e)return null;let t;try{t=Ea(e??"",this.manifestUrlString)}catch(r){this.error$.next({id:"ManifestParsing",category:s.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:r})}if(!t)return null;const i=({kind:r,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&Be()?.isTypeSupported?.(`${n}; codecs="${o}"`)||r===Z.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(([r,n])=>[r,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.manifestUrlString=me(this.manifestUrlString,t,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,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(ce.REPRESENTATIOS_READY);const r=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(r(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),this.tuning.useManagedMediaSource&&Fi())if(i){const p=document.createElement("source");r(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 di(Z.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,o),this.bufferManagers=[this.videoBufferManager],s.isNonNullable(t)&&(this.audioBufferManager=new di(Z.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(Je).subscribe(p=>{if(this.element?.paused){const m=ei(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=me(this.manifestUrlString,m+Je,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(s.merge(...hi.filter(p=>p!=="waiting").map(p=>s.fromEvent(this.element,p))).pipe(s.map(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),s.filterChanged(),s.filter(p=>!!p),s.tap(p=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=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),Na(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??b))-b}this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let p=0;this.representationSubscription.add(s.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(s.throttle(Je)).subscribe(async({liveLoadBufferLength:m,bufferLength:T})=>{if(s.assertNonNullable(this.element),this.isUpdatingLive)return;const b=this.element.playbackRate,y=ei(this.manifestUrlString,X.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,F=this.isActiveLowLatency?T:m;let B=ye.None;if(this.isActiveLowLatency?B=ye.ActiveLowLatency:F<P+E&&F>=P?B=ye.LiveWithTargetOffset:y!==0&&F<P&&(B=ye.LiveForwardBuffering),isFinite(m)&&(p=m>p?m:p),B===ye.LiveForwardBuffering||B===ye.LiveWithTargetOffset){const R=p-(P+g),V=this.normolizeLiveOffset(Math.trunc(y+R/b)),k=Math.abs(V-y);let w;!m||k<=this.tuning.dashCmafLive.offsetCalculationError?w=y:V>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=V:w=0,this.manifestUrlString=me(this.manifestUrlString,w,X.DASH_CMAF_OFFSET_P)}B!==ye.None&&B!==ye.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(ce.REPRESENTATIOS_READY)}.bind(this));initBuffer(){s.assertNonNullable(this.element),this.state$.setState(ce.RUNNING),this.subscription.add(s.merge(...hi.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&&Ht(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const e=()=>{if(this.element){if(this.timeInWaiting+=Je,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=s.interval(Je).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:s.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{[Z.VIDEO]:this.videoBufferManager,[Z.AUDIO]:this.audioBufferManager,[Z.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),Ht(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(ce.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}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=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const n of this.bufferManagers)for(const o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-r<=t&&o.to+r>t&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){const n=Math.max(...i)+10;n===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=n/1e3}}};class Va{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class _a{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 r=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:r,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 r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var Fa=`#define GLSLIFY 1
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;}`,Oa=`#ifdef GL_ES
39
39
  precision highp float;precision highp int;
40
40
  #else
41
41
  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 Oa{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 r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ma(this.params.fov,this.params.orientation),this.cameraRotationManager=new Va(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"),r=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(r,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(_a,this.gl.VERTEX_SHADER),i=this.createShader(Fa,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 r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/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,r=this.camera.fov.y/180/2,n=e-i,o=t-r,c=e+i,u=t-r,l=e+i,d=t+r,h=e-i,f=t+r;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 Yt=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,Ua=(a,e)=>new s.Observable(t=>{if(!window.IntersectionObserver)return;const i={root:null},r=new IntersectionObserver((o,c)=>{o.forEach(u=>t.next(u.isIntersecting||Yt()))},{...i,...e});r.observe(a);const n=s.fromEvent(document,"visibilitychange").pipe(s.map(o=>!document.hidden||Yt())).subscribe(o=>t.next(o));return()=>{r.unobserve(a),n.unsubscribe}});class Fi{scene3D;subscription=new s.Subscription;videoState=new z(Y.STOPPED);video;player;params;elementSize$=new s.ValueSubject(void 0);elementVisible$=new s.ValueSubject(!0);textTracksManager=new Ne;droppedFramesManager=new Pi;videoTracks$=new s.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new vs;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Ue(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(ke(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ba({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Ye(this.video),r=this.constructor.name,n=c=>{e.error$.next({id:r,category:s.ErrorCategory.WTF,message:`${r} 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:r,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$,r)),this.subscription.add(ft(this.video,t.isLooped,r)),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(tt(this.video,t.playbackRate,i.playbackRateState$,r)),n(s.observeElementSize(this.video),this.elementSize$),n(Ua(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l===ce.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=ka(b);y&&this.audioTracks.push({track:y,representation:b})}for(const b of p){const y=Ea(b);if(y){d.push({track:y,representation:b});const C=!this.params.tuning.isAudioDisabled&&Aa(f,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(d);for(const b of m){const y=wa(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===ce.REPRESENTATIOS_READY&&(this.videoState.setState(Y.READY),this.player.initBuffer())},r));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!==ce.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 C=s.videoSizeToQuality(y),P=s.videoSizeToQuality(h);if(C&&P)return s.isLowerOrEqual(C,P)&&s.isLowerOrEqual(C,m)}).map(y=>y.id)[0]),this.player.switchRepresentation(Z.VIDEO,T).catch(o);const b=this.audioRepresentations.get(h.id);b&&this.player.switchRepresentation(Z.AUDIO,b.id).catch(o)}},r)),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$,r)),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)},r)),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,r))}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,r=this.params.output.currentVideoTrack$.getValue(),n=ct(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,r?this.audioRepresentations.get(r.id)?.bitrate??0:0),l=Ct(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:r,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(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state===I.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Y.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-o,r.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),A(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),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&A(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&&A(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&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Oa(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(){Ge(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Y.PAUSED),A(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),He(this.video)}}class Ha extends Fi{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class ja extends Fi{constructor(e){super(e),this.liveOffset=new qt}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(Je),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()===Y.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(s.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(s.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=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,r)})}}const ge={};var M;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(M||(M={}));const nt=(a,e)=>new s.Observable(t=>{const i=(r,n)=>t.next(n);return a.on(e,i),()=>a.off(e,i)});class Ya{subscription=new s.Subscription;videoState=new z(M.INITIALIZING);video;params;hls;textTracksManager=new Ne;trackLevels=new Map;constructor(e){this.video=Ue(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(ke(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),He(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:s.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(ge.Hls=r.default,ge.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(ge.Hls,"hls.js not loaded"),this.hls=new ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){s.assertNonNullable(ge.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})},r=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ft(this.video,e.isLooped,i)),this.subscription.add(je(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(tt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(nt(this.hls,ge.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(r.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},i)),n(nt(this.hls,ge.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=Pt(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(nt(this.hls,ge.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(nt(this.hls,ge.Events.LEVEL_LOADING).pipe(s.map(({url:l})=>ke(l))),t.hostname$),this.subscription.add(we(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=nt(this.hls,ge.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(we(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(r.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(),r=this.params.desiredState.seekState.getState();if(e!==M.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&r.state===I.Requested&&this.seek(r.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),A(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 Ge(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),A(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),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const hi="X-Playback-Duration";var fi=async a=>{const e=await dt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(hi)?parseInt(e.headers.get(hi),10):void 0};const Ga=a=>{let e=null;if(a.QUALITY&&(e=Pt(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=s.videoSizeToQuality({width:t,height:i})}return e??null},qa=(a,e)=>{const t=a.split(`
46
- `),i=[],r=[];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=Ga(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&&r.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:r}},za=a=>new Promise(e=>{setTimeout(()=>{e()},a)});let Vt=0;const Jt=async(a,e=a,t)=>{const r=await(await dt(a)).text();Vt+=1;try{const{qualityManifests:n,textTracks:o}=qa(r,e);return{qualityManifests:n,textTracks:o}}catch{if(Vt<=t.manifestRetryMaxCount)return await za(s.getExponentialDelay(Vt-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Jt(a,e,t)}return{qualityManifests:[],textTracks:[]}};var U;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(U||(U={}));class Wa{subscription=new s.Subscription;videoState=new z(U.STOPPED);video;params;textTracksManager=new Ne;masterManifest;manifests$=new s.ValueSubject([]);maxSeekBackTime$;liveOffset=new qt;manifestStartTime$=new s.ValueSubject(void 0);constructor(e){this.params=e,this.video=Ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url},Jt(me(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(ke(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(),r=t.getTransition(),n=r?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!r&&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})},r=Ye(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,i));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.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(r.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(ke(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(r.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:r.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),He(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(),r=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&&r.searchParams.set(d,h)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?X.DASH_CMAF_OFFSET_P:X.OFFSET_P,o=me(r.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{dt(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(){Ge(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),A(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(),r=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),A(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(r?.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?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),A(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()):r?.to===exports.PlaybackState.PLAYING&&A(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 r?.to===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case U.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var j;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(j||(j={}));class Qa{subscription=new s.Subscription;videoState=new z(j.STOPPED);video;params;textTracksManager=new Ne;masterManifest;manifests$=new s.ValueSubject([]);constructor(e){this.params=e,this.video=Ue(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Jt(me(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(),r=t.getTransition(),n=r?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!r&&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})},r=Ye(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u));if(n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===j.READY&&this.videoState.setState(j.READY),this.videoState.getState()===j.PLAYING&&this.playIfAllowed()},i).add(r.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(ke(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),He(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(),r=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&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(j.PAUSED),A(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(),r=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),A(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(r?.to!==exports.PlaybackState.PAUSED&&l.state===I.Requested&&this.seek(l.position),t){case j.READY:i===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(j.PAUSED),A(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()):r?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case j.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed()):r?.to===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case j.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var q;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(q||(q={}));class Ja{subscription=new s.Subscription;videoState=new z(q.STOPPED);video;trackUrls={};params;textTracksManager=new Ne;constructor(e){this.params=e,this.video=Ue(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const n=r.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})},r=Ye(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.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()===q.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),He(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=Ht(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ke(t))}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),A(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!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),A(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!==q.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===q.STOPPED){this.videoState.startTransitionTo(q.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 q.READY:t===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&A(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 r=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(r&&o&&s.isHigherOrEqual(o.quality,r.quality)&&(t=r),!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 r=Object.values(this.trackUrls).map(n=>n.track);t=Ct(r,{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"],Xa=1e3,Ka=3,_t=()=>null;class Za{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),Xa)}normalizeOptions(e={}){const t={stunServerList:pi,maxRetryNumber:Ka,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var H;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(H||(H={}));class er{subscription;params;log;video;videoState=new z(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=Ue(e.container),this.liveStreamClient=new Za(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),He(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 r=Ye(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(je(this.video,t.volume,r.volumeState$,i)).add(r.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(ke(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,A(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(){Ge(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),A(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),A(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),A(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&&A(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&&A(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}}var ie;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg",a.DASH_ANY_MPEG="dash_any_mpeg",a.DASH_ANY_WEBM="dash_any_webm",a.DASH_SEP="dash_sep"})(ie||(ie={}));var Re;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(Re||(Re={}));const Oi=s.getCurrentBrowser().device===s.CurrentClientDevice.Android,$t=document.createElement("video"),tr='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ir='video/mp4; codecs="hev1.1.6.L93.B0"',Ui='video/webm; codecs="vp09.00.10.08"',Hi='video/webm; codecs="av01.0.00M.08"',sr='audio/mp4; codecs="mp4a.40.2"',ar='audio/webm; codecs="opus"',Me={mms:_i(),mse:Na(),hls:!!($t.canPlayType?.("application/x-mpegurl")||$t.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},oe={mp4:!!$t.canPlayType?.("video/mp4"),webm:!!$t.canPlayType?.("video/webm"),cmaf:!0},Ee={h264:!!Be()?.isTypeSupported?.(tr),h265:!!Be()?.isTypeSupported?.(ir),vp9:!!Be()?.isTypeSupported?.(Ui),av1:!!Be()?.isTypeSupported?.(Hi),aac:!!Be()?.isTypeSupported?.(sr),opus:!!Be()?.isTypeSupported?.(ar)},ot=(Ee.h264||Ee.h265)&&Ee.aac;let Ve;const rr=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Hi}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Ui}})]);Ve={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{rr()}catch(a){console.error(a)}const ht=Me.hls&&oe.mp4,nr=()=>Object.keys(Ee).filter(a=>Ee[a]),or=(a,e=!1,t=!1)=>{const i=Me.mse||Me.mms&&t;return a.filter(r=>{switch(r){case exports.VideoFormat.DASH_SEP:return i&&oe.mp4&&ot;case exports.VideoFormat.DASH_WEBM:return i&&oe.webm&&Ee.vp9&&Ee.opus;case exports.VideoFormat.DASH_WEBM_AV1:return i&&oe.webm&&Ee.av1&&Ee.opus;case exports.VideoFormat.DASH_LIVE:return Me.mse&&oe.mp4&&ot;case exports.VideoFormat.DASH_LIVE_CMAF:return i&&oe.mp4&&ot&&oe.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return i&&oe.mp4&&ot;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ht||e&&Me.mse&&oe.mp4&&ot;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ht;case exports.VideoFormat.MPEG:return oe.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&Ee.h264&&(oe.mp4||oe.webm);default:return s.assertNever(r)}})},xe=a=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(a){case Re.VP9:return[e,t];case Re.AV1:return[t,e];case Re.NONE:return[];case Re.SMOOTH:return Ve?Ve[t].smooth?[t,e]:Ve[e].smooth?[e,t]:[t,e]:[e,t];case Re.POWER_EFFICIENT:return Ve?Ve[t].powerEfficient?[t,e]:Ve[e].powerEfficient?[e,t]:[t,e]:[e,t];default:s.assertNever(a)}return[e,t]},cr=({webmCodec:a,androidPreferredFormat:e})=>{if(Oi)switch(e){case ie.MPEG:return[exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case ie.DASH:return[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];case ie.DASH_ANY_MPEG:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.DASH_ANY_WEBM:return[...xe(a),exports.VideoFormat.MPEG,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.DASH_SEP:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];default:s.assertNever(e)}return ht?[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},lr=({androidPreferredFormat:a,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],r=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...r],o=[...r,...i];let c;if(Oi)switch(a){case ie.DASH:case ie.DASH_ANY_MPEG:case ie.DASH_ANY_WEBM:case ie.DASH_SEP:{c=n;break}case ie.HLS:case ie.MPEG:{c=o;break}default:s.assertNever(a)}else ht?c=o:c=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...c]:[...c,exports.VideoFormat.WEB_RTC_LIVE]},Si=a=>a?[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 ur=a=>new s.Observable(e=>{const t=new s.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(s.map(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,n=a.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),a.maxTransitionInterval)})),t.add(r.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),a.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const dr={chunkDuration:5e3,maxParallelRequests:5};class hr{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=or([...lr(this.params.tuning),...cr(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(c=>s.isNonNullable(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let n=[];i?n=[i]:r.length?n=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.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(r){this.providerError$.next({id:"ProviderNotConstructed",category:s.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}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(),r=i.state!==I.None;if(this.params.desiredState.seekState.setState({state:I.Requested,position:r?i.position:t,forcePrecise:r?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 ee.SCREEN:return this.createScreenProvider(t);case ee.CHROMECAST:return this.createChromecastProvider(t);default:return s.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,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 Ha({...o,source:c,sourceHls:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new ja({...o,source:c})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),ht||!this.params.tuning.useHlsJs?new Qa({...o,source:c}):new Ya({...o,source:c})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Wa({...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 Ja({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Bs({...o,source:c,config:{...dr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new er({container:i,source:c,desiredState:r,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:r,meta:n}=this.params,o=this.providerOutput,c=this.params.dependencies.chromecastInitializer.connection$.getValue();return s.assertNonNullable(c),new os({connection:c,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ee.CHROMECAST:ee.SCREEN}chooseFormat(e){switch(e){case ee.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ee.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return s.assertNever(e)}}skipFormat(e){switch(e){case ee.SCREEN:return this.screenFormatsIterator.next();case ee.CHROMECAST:return this.chromecastFormatsIterator.next();default:return s.assertNever(e)}}handleNoFormatsError(e){switch(e){case ee.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ee.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=r=>{const n=new URL(r);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(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new s.Subscription;let t=!1,i=0;return e.add(s.merge(this.providerOutput.error$,ur({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(s.map(r=>({id:`ProviderHangup:${r}`,category:s.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(s.filter(({to:n})=>n===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const n=this.current$.getValue().destination;if(n===ee.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ee.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=r.category===s.ErrorCategory.NETWORK,c=r.category===s.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!c;u&&!c&&(o&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider(n??ee.SCREEN)}})),e}}const fr=5e3,bi="one_video_throughput",gi="one_video_rtt",lt=window.navigator.connection,yi=()=>{const a=lt?.downlink;if(s.isNonNullable(a)&&a!==10)return a*1e3},vi=()=>{const a=lt?.rtt;if(s.isNonNullable(a)&&a!==3e3)return a},Ti=(a,e,t)=>{const i=t*8,r=i/a;return i/(r+e)};class ut{throughput;rtt;subscription=new s.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=ut.load(bi)||(e.useBrowserEstimation?yi():void 0)||fr,i=ut.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=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){const r=()=>{const o=yi();o&&this.throughput.next(o);const c=vi();s.isNonNullable(c)&&this.rtt.next(c)};lt&&"onchange"in lt&&this.subscription.add(s.fromEvent(lt,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{s.safeStorage.set(bi,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{s.safeStorage.set(gi,r.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:r,rtt:n})=>Ti(r,n,e.rttPenaltyRequestSize)),s.filter(r=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=s.now();const r=new s.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(s.fromEvent(e,"progress").pipe(s.once()).subscribe(n=>{t=n.loaded,i=s.now()}));break;case 1:case 0:r.add(s.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=s.now()}));break}r.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),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=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(r,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 r+=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,r=!1){if(ut.sanityCheck(e,t,r)){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 r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<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,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:2e4,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:Re.VP9,androidPreferredFormat:ie.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,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}},pr=a=>({...s.fillWithDefault(a,Ei),configName:[...a.configName??[],...Ei.configName]});var ki=({seekState:a,position$:e})=>s.merge(a.stateChangeEnded$.pipe(s.map(({to:t})=>t.state===I.None?void 0:(t.position??NaN)/1e3),s.filter(s.isNonNullable)),e.pipe(s.filter(()=>a.getState().state===I.None))),mr=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return s.assertNonNullable(e,`Wrong container or containerId {${a.container}}`),e};const Sr=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(s.filter(r=>r.length>0),s.once()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class br{subscription=new s.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new s.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;hasLiveOffsetByPaused=new s.ValueSubject(!1);hasLiveOffsetByPausedTimer=0;desiredState={playbackState:new z(exports.PlaybackState.STOPPED),seekState:new z({state:I.None}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),playbackRate:new z(1),externalTextTracks:new z([]),internalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({}),cameraOrientation:new z({x:0,y:0})};info={playbackState$:new s.ValueSubject(exports.PlaybackState.STOPPED),position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),muted$:new s.ValueSubject(!1),volume$:new s.ValueSubject(1),availableQualities$:new s.ValueSubject([]),availableQualitiesFps$:new s.ValueSubject({}),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),currentQuality$:new s.ValueSubject(void 0),isAutoQualityEnabled$:new s.ValueSubject(!0),autoQualityLimitingAvailable$:new s.ValueSubject(!1),autoQualityLimits$:new s.ValueSubject({}),currentPlaybackRate$:new s.ValueSubject(1),currentBuffer$:new s.ValueSubject({start:0,end:0}),isBuffering$:new s.ValueSubject(!0),isStalled$:new s.ValueSubject(!1),isEnded$:new s.ValueSubject(!1),isLooped$:new s.ValueSubject(!1),isLive$:new s.ValueSubject(void 0),canChangePlaybackSpeed$:new s.ValueSubject(void 0),atLiveEdge$:new s.ValueSubject(void 0),atLiveDurationEdge$:new s.ValueSubject(void 0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),currentFormat$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),throughputEstimation$:new s.ValueSubject(void 0),rttEstimation$:new s.ValueSubject(void 0),videoBitrate$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),surface$:new s.ValueSubject(exports.Surface.NONE),chromecastState$:new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new s.ValueSubject(void 0),intrinsicVideoSize$:new s.ValueSubject(void 0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1)};events={inited$:new s.Subject,ready$:new s.Subject,started$:new s.Subject,playing$:new s.Subject,paused$:new s.Subject,stopped$:new s.Subject,willStart$:new s.Subject,willResume$:new s.Subject,willPause$:new s.Subject,willStop$:new s.Subject,willDestruct$:new s.Subject,watchCoverageRecord$:new s.Subject,watchCoverageLive$:new s.Subject,managedError$:new s.Subject,fatalError$:new s.Subject,ended$:new s.Subject,looped$:new s.Subject,seeked$:new s.Subject,willSeek$:new s.Subject,firstBytes$:new s.Subject,firstFrame$:new s.Subject,canplay$:new s.Subject,log$:new s.Subject};experimental={element$:new s.ValueSubject(void 0),tuningConfigName$:new s.ValueSubject([]),enableDebugTelemetry$:new s.ValueSubject(!1),dumpTelemetry:bs};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=pr(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ts({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ut(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,r);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=mr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new hr({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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),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&&!Yt()?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(),r=this.info.isLive$.getValue();return e>=i&&!r&&(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 Sr(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 r=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.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:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||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({hasLiveOffsetByPaused:s.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(s.map(o=>o.to),s.filterChanged(),s.map(o=>o===exports.PlaybackState.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:o,isLowLatency:c})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),o){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(c));return}this.hasLiveOffsetByPaused.next(!1)})).add(s.combine({atLiveEdge: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=this.getActiveLiveDelay(u);return o&&Math.abs(c)<l/1e3}),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(s.map(({atLiveEdge:o,hasPausedTimeoutCase:c})=>o&&!c)).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 r=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?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),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,r)=>i.provider===r.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:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ct(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),Ss(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ms(t)),this.providerContainer.current$.subscribe(({type:t})=>yt("provider",t)),e.duration$.subscribe(t=>yt("duration",t)),e.availableVideoTracks$.pipe(s.filter(t=>!!t.length),s.once()).subscribe(t=>yt("tracks",t)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(s.map(t=>t?.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(t=>this.subscription.add(t)),yt("codecs",nr())}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(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:s.ErrorCategory.DOM,message:String(r)})})};this.subscription.add(s.merge(s.fromEvent(document,"visibilitychange"),s.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;r&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const gr=`@vkontakte/videoplayer-core@${Ai}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return s.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return s.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return s.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return s.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return s.VideoQuality}});exports.Player=br;exports.SDK_VERSION=gr;exports.VERSION=Ai;
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 Ua{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Va(this.params.fov,this.params.orientation),this.cameraRotationManager=new _a(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"),r=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(r,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Fa,this.gl.VERTEX_SHADER),i=this.createShader(Oa,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/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,r=this.camera.fov.y/180/2,n=e-i,o=t-r,c=e+i,u=t-r,l=e+i,d=t+r,h=e-i,f=t+r;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}}class Oi{scene3D;subscription=new s.Subscription;videoState=new z(Y.STOPPED);video;player;params;elementSize$=new s.ValueSubject(void 0);textTracksManager=new Ne;droppedFramesManager=new Ci;videoTracks$=new s.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Ts;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Ue(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(ke(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ma({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=Ye(this.video),r=this.constructor.name,n=c=>{e.error$.next({id:r,category:s.ErrorCategory.WTF,message:`${r} 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:r,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$,r)),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(tt(this.video,t.playbackRate,i.playbackRateState$,r)),n(s.observeElementSize(this.video),this.elementSize$),n(it(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l===ce.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=Aa(b);y&&this.audioTracks.push({track:y,representation:b})}for(const b of p){const y=ka(b);if(y){d.push({track:y,representation:b});const C=!this.params.tuning.isAudioDisabled&&wa(f,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(d);for(const b of m){const y=$a(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===ce.REPRESENTATIOS_READY&&(this.videoState.setState(Y.READY),this.player.initBuffer())},r));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.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).subscribe(()=>{const l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!==ce.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.params.output.elementVisible$.getValue()&&p&&(T=this.videoTracks$.getValue().map(y=>y.representation).sort((y,C)=>C.bitrate-y.bitrate).filter(y=>{const C=s.videoSizeToQuality(y),P=s.videoSizeToQuality(h);if(C&&P)return s.isLowerOrEqual(C,P)&&s.isLowerOrEqual(C,m)}).map(y=>y.id)[0]),this.player.switchRepresentation(Z.VIDEO,T).catch(o);const b=this.audioRepresentations.get(h.id);b&&this.player.switchRepresentation(Z.AUDIO,b.id).catch(o)}},r)),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$,r)),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)},r)),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,r))}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,r=this.params.output.currentVideoTrack$.getValue(),n=lt(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,r?this.audioRepresentations.get(r.id)?.bitrate??0:0),l=Dt(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:r,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(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state===I.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Y.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-o,r.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),A(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),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&A(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&&A(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&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ua(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){Ge(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Y.PAUSED),A(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),He(this.video)}}class Ha extends Oi{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class ja extends Oi{constructor(e){super(e),this.liveOffset=new 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(Je),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()===Y.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(s.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(s.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=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,r)})}}const ge={};var M;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(M||(M={}));const ot=(a,e)=>new s.Observable(t=>{const i=(r,n)=>t.next(n);return a.on(e,i),()=>a.off(e,i)});class Ya{subscription=new s.Subscription;videoState=new z(M.INITIALIZING);video;params;hls;textTracksManager=new Ne;trackLevels=new Map;constructor(e){this.video=Ue(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(ke(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),He(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:s.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(ge.Hls=r.default,ge.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(ge.Hls,"hls.js not loaded"),this.hls=new ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){s.assertNonNullable(ge.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})},r=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(pt(this.video,e.isLooped,i)),this.subscription.add(je(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(tt(this.video,e.playbackRate,r.playbackRateState$,i)),n(it(this.video),t.elementVisible$),this.subscription.add(ot(this.hls,ge.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(r.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},i)),n(ot(this.hls,ge.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=Ct(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(ot(this.hls,ge.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(ot(this.hls,ge.Events.LEVEL_LOADING).pipe(s.map(({url:l})=>ke(l))),t.hostname$),this.subscription.add(we(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=ot(this.hls,ge.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(we(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(r.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(),r=this.params.desiredState.seekState.getState();if(e!==M.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&r.state===I.Requested&&this.seek(r.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),A(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 Ge(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),A(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),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const fi="X-Playback-Duration";var pi=async a=>{const e=await ht(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(fi)?parseInt(e.headers.get(fi),10):void 0};const Ga=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=s.videoSizeToQuality({width:t,height:i})}return e??null},qa=(a,e)=>{const t=a.split(`
46
+ `),i=[],r=[];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=Ga(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&&r.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:r}},za=a=>new Promise(e=>{setTimeout(()=>{e()},a)});let _t=0;const Xt=async(a,e=a,t)=>{const r=await(await ht(a)).text();_t+=1;try{const{qualityManifests:n,textTracks:o}=qa(r,e);return{qualityManifests:n,textTracks:o}}catch{if(_t<=t.manifestRetryMaxCount)return await za(s.getExponentialDelay(_t-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xt(a,e,t)}return{qualityManifests:[],textTracks:[]}};var U;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(U||(U={}));class Wa{subscription=new s.Subscription;videoState=new z(U.STOPPED);video;params;textTracksManager=new Ne;masterManifest;manifests$=new s.ValueSubject([]);maxSeekBackTime$;liveOffset=new zt;manifestStartTime$=new s.ValueSubject(void 0);constructor(e){this.params=e,this.video=Ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url},Xt(me(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(ke(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(),r=t.getTransition(),n=r?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!r&&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})},r=Ye(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,i));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,i)),n(it(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.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(r.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(ke(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(r.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:r.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),He(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(),r=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&&r.searchParams.set(d,h)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?X.DASH_CMAF_OFFSET_P:X.OFFSET_P,o=me(r.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),pi(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{ht(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();pi(h).then(f=>{s.isNullable(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),A(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(),r=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),A(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(r?.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?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),A(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()):r?.to===exports.PlaybackState.PLAYING&&A(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 r?.to===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case U.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var j;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(j||(j={}));class Qa{subscription=new s.Subscription;videoState=new z(j.STOPPED);video;params;textTracksManager=new Ne;masterManifest;manifests$=new s.ValueSubject([]);constructor(e){this.params=e,this.video=Ue(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Xt(me(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(),r=t.getTransition(),n=r?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!r&&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})},r=Ye(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u));if(n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(pt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===j.READY&&this.videoState.setState(j.READY),this.videoState.getState()===j.PLAYING&&this.playIfAllowed()},i).add(r.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(ke(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),He(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(),r=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&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(j.PAUSED),A(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(),r=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),A(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(r?.to!==exports.PlaybackState.PAUSED&&l.state===I.Requested&&this.seek(l.position),t){case j.READY:i===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(j.PAUSED),A(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()):r?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case j.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed()):r?.to===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case j.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var q;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(q||(q={}));class Ja{subscription=new s.Subscription;videoState=new z(q.STOPPED);video;trackUrls={};params;textTracksManager=new Ne;constructor(e){this.params=e,this.video=Ue(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const n=r.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})},r=Ye(this.video),n=(c,u)=>this.subscription.add(c.subscribe(u,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(pt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,i)),n(it(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.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()===q.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),He(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=Yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ke(t))}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),A(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!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),A(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!==q.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===q.STOPPED){this.videoState.startTransitionTo(q.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 q.READY:t===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&A(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 r=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(r&&o&&s.isHigherOrEqual(o.quality,r.quality)&&(t=r),!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 r=Object.values(this.trackUrls).map(n=>n.track);t=Dt(r,{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 mi=["stun:videostun.mycdn.me:80"],Xa=1e3,Ka=3,Ft=()=>null;class Za{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ft;externalStopCallback=Ft;externalErrorCallback=Ft;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:mi}]};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),Xa)}normalizeOptions(e={}){const t={stunServerList:mi,maxRetryNumber:Ka,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var H;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(H||(H={}));class er{subscription;params;log;video;videoState=new z(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=Ue(e.container),this.liveStreamClient=new Za(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),He(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 r=Ye(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(it(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(je(this.video,t.volume,r.volumeState$,i)).add(r.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(ke(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,A(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(){Ge(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),A(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),A(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),A(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&&A(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&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}}class Si{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}}var ie;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg",a.DASH_ANY_MPEG="dash_any_mpeg",a.DASH_ANY_WEBM="dash_any_webm",a.DASH_SEP="dash_sep"})(ie||(ie={}));var Re;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(Re||(Re={}));const Ui=s.getCurrentBrowser().device===s.CurrentClientDevice.Android,Pt=document.createElement("video"),tr='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ir='video/mp4; codecs="hev1.1.6.L93.B0"',Hi='video/webm; codecs="vp09.00.10.08"',ji='video/webm; codecs="av01.0.00M.08"',sr='audio/mp4; codecs="mp4a.40.2"',ar='audio/webm; codecs="opus"',Me={mms:Fi(),mse:Ia(),hls:!!(Pt.canPlayType?.("application/x-mpegurl")||Pt.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},oe={mp4:!!Pt.canPlayType?.("video/mp4"),webm:!!Pt.canPlayType?.("video/webm"),cmaf:!0},Ee={h264:!!Be()?.isTypeSupported?.(tr),h265:!!Be()?.isTypeSupported?.(ir),vp9:!!Be()?.isTypeSupported?.(Hi),av1:!!Be()?.isTypeSupported?.(ji),aac:!!Be()?.isTypeSupported?.(sr),opus:!!Be()?.isTypeSupported?.(ar)},ct=(Ee.h264||Ee.h265)&&Ee.aac;let Ve;const rr=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:ji}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Hi}})]);Ve={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{rr()}catch(a){console.error(a)}const ft=Me.hls&&oe.mp4,nr=()=>Object.keys(Ee).filter(a=>Ee[a]),or=(a,e=!1,t=!1)=>{const i=Me.mse||Me.mms&&t;return a.filter(r=>{switch(r){case exports.VideoFormat.DASH_SEP:return i&&oe.mp4&&ct;case exports.VideoFormat.DASH_WEBM:return i&&oe.webm&&Ee.vp9&&Ee.opus;case exports.VideoFormat.DASH_WEBM_AV1:return i&&oe.webm&&Ee.av1&&Ee.opus;case exports.VideoFormat.DASH_LIVE:return Me.mse&&oe.mp4&&ct;case exports.VideoFormat.DASH_LIVE_CMAF:return i&&oe.mp4&&ct&&oe.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return i&&oe.mp4&&ct;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ft||e&&Me.mse&&oe.mp4&&ct;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ft;case exports.VideoFormat.MPEG:return oe.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&Ee.h264&&(oe.mp4||oe.webm);default:return s.assertNever(r)}})},xe=a=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(a){case Re.VP9:return[e,t];case Re.AV1:return[t,e];case Re.NONE:return[];case Re.SMOOTH:return Ve?Ve[t].smooth?[t,e]:Ve[e].smooth?[e,t]:[t,e]:[e,t];case Re.POWER_EFFICIENT:return Ve?Ve[t].powerEfficient?[t,e]:Ve[e].powerEfficient?[e,t]:[t,e]:[e,t];default:s.assertNever(a)}return[e,t]},cr=({webmCodec:a,androidPreferredFormat:e})=>{if(Ui)switch(e){case ie.MPEG:return[exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case ie.DASH:return[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];case ie.DASH_ANY_MPEG:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.DASH_ANY_WEBM:return[...xe(a),exports.VideoFormat.MPEG,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.DASH_SEP:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];default:s.assertNever(e)}return ft?[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},lr=({androidPreferredFormat:a,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],r=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...r],o=[...r,...i];let c;if(Ui)switch(a){case ie.DASH:case ie.DASH_ANY_MPEG:case ie.DASH_ANY_WEBM:case ie.DASH_SEP:{c=n;break}case ie.HLS:case ie.MPEG:{c=o;break}default:s.assertNever(a)}else ft?c=o:c=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...c]:[...c,exports.VideoFormat.WEB_RTC_LIVE]},bi=a=>a?[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 ur=a=>new s.Observable(e=>{const t=new s.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(s.map(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,n=a.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),a.maxTransitionInterval)})),t.add(r.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),a.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const dr={chunkDuration:5e3,maxParallelRequests:5};class hr{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),elementVisible$:new s.ValueSubject(!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=or([...lr(this.params.tuning),...cr(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(c=>s.isNonNullable(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let n=[];i?n=[i]:r.length?n=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Si(n);const o=[...bi(!0),...bi(!1)];this.chromecastFormatsIterator=new Si(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(r){this.providerError$.next({id:"ProviderNotConstructed",category:s.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}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(),r=i.state!==I.None;if(this.params.desiredState.seekState.setState({state:I.Requested,position:r?i.position:t,forcePrecise:r?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 ee.SCREEN:return this.createScreenProvider(t);case ee.CHROMECAST:return this.createChromecastProvider(t);default:return s.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,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 Ha({...o,source:c,sourceHls:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new ja({...o,source:c})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),ft||!this.params.tuning.useHlsJs?new Qa({...o,source:c}):new Ya({...o,source:c})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Wa({...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 Ja({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Ms({...o,source:c,config:{...dr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new er({container:i,source:c,desiredState:r,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:r,meta:n}=this.params,o=this.providerOutput,c=this.params.dependencies.chromecastInitializer.connection$.getValue();return s.assertNonNullable(c),new cs({connection:c,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ee.CHROMECAST:ee.SCREEN}chooseFormat(e){switch(e){case ee.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ee.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return s.assertNever(e)}}skipFormat(e){switch(e){case ee.SCREEN:return this.screenFormatsIterator.next();case ee.CHROMECAST:return this.chromecastFormatsIterator.next();default:return s.assertNever(e)}}handleNoFormatsError(e){switch(e){case ee.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ee.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=r=>{const n=new URL(r);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(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new s.Subscription;let t=!1,i=0;return e.add(s.merge(this.providerOutput.error$,ur({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(s.map(r=>({id:`ProviderHangup:${r}`,category:s.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(s.filter(({to:n})=>n===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const n=this.current$.getValue().destination;if(n===ee.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ee.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=r.category===s.ErrorCategory.NETWORK,c=r.category===s.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!c;u&&!c&&(o&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider(n??ee.SCREEN)}})),e}}const fr=5e3,gi="one_video_throughput",yi="one_video_rtt",ut=window.navigator.connection,vi=()=>{const a=ut?.downlink;if(s.isNonNullable(a)&&a!==10)return a*1e3},Ti=()=>{const a=ut?.rtt;if(s.isNonNullable(a)&&a!==3e3)return a},Ei=(a,e,t)=>{const i=t*8,r=i/a;return i/(r+e)};class dt{throughput;rtt;subscription=new s.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=dt.load(gi)||(e.useBrowserEstimation?vi():void 0)||fr,i=dt.load(yi)??(e.useBrowserEstimation?Ti():void 0)??0;if(this.throughput$=new s.ValueSubject(t),this.rtt$=new s.ValueSubject(i),this.rttAdjustedThroughput$=new s.ValueSubject(Ei(t,i,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(i,1,e),e.useBrowserEstimation){const r=()=>{const o=vi();o&&this.throughput.next(o);const c=Ti();s.isNonNullable(c)&&this.rtt.next(c)};ut&&"onchange"in ut&&this.subscription.add(s.fromEvent(ut,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{s.safeStorage.set(gi,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{s.safeStorage.set(yi,r.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:r,rtt:n})=>Ei(r,n,e.rttPenaltyRequestSize)),s.filter(r=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=s.now();const r=new s.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(s.fromEvent(e,"progress").pipe(s.once()).subscribe(n=>{t=n.loaded,i=s.now()}));break;case 1:case 0:r.add(s.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=s.now()}));break}r.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),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=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(r,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 r+=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,r=!1){if(dt.sanityCheck(e,t,r)){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 r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<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 ki={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,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,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:2e4,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:Re.VP9,androidPreferredFormat:ie.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,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}},pr=a=>({...s.fillWithDefault(a,ki),configName:[...a.configName??[],...ki.configName]});var Ai=({seekState:a,position$:e})=>s.merge(a.stateChangeEnded$.pipe(s.map(({to:t})=>t.state===I.None?void 0:(t.position??NaN)/1e3),s.filter(s.isNonNullable)),e.pipe(s.filter(()=>a.getState().state===I.None))),mr=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return s.assertNonNullable(e,`Wrong container or containerId {${a.container}}`),e};const Sr=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(s.filter(r=>r.length>0),s.once()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class br{subscription=new s.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new s.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;hasLiveOffsetByPaused=new s.ValueSubject(!1);hasLiveOffsetByPausedTimer=0;desiredState={playbackState:new z(exports.PlaybackState.STOPPED),seekState:new z({state:I.None}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),playbackRate:new z(1),externalTextTracks:new z([]),internalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({}),cameraOrientation:new z({x:0,y:0})};info={playbackState$:new s.ValueSubject(exports.PlaybackState.STOPPED),position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),muted$:new s.ValueSubject(!1),volume$:new s.ValueSubject(1),availableQualities$:new s.ValueSubject([]),availableQualitiesFps$:new s.ValueSubject({}),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),currentQuality$:new s.ValueSubject(void 0),isAutoQualityEnabled$:new s.ValueSubject(!0),autoQualityLimitingAvailable$:new s.ValueSubject(!1),autoQualityLimits$:new s.ValueSubject({}),currentPlaybackRate$:new s.ValueSubject(1),currentBuffer$:new s.ValueSubject({start:0,end:0}),isBuffering$:new s.ValueSubject(!0),isStalled$:new s.ValueSubject(!1),isEnded$:new s.ValueSubject(!1),isLooped$:new s.ValueSubject(!1),isLive$:new s.ValueSubject(void 0),canChangePlaybackSpeed$:new s.ValueSubject(void 0),atLiveEdge$:new s.ValueSubject(void 0),atLiveDurationEdge$:new s.ValueSubject(void 0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),currentFormat$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),throughputEstimation$:new s.ValueSubject(void 0),rttEstimation$:new s.ValueSubject(void 0),videoBitrate$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),surface$:new s.ValueSubject(exports.Surface.NONE),chromecastState$:new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new s.ValueSubject(void 0),intrinsicVideoSize$:new s.ValueSubject(void 0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1)};events={inited$:new s.Subject,ready$:new s.Subject,started$:new s.Subject,playing$:new s.Subject,paused$:new s.Subject,stopped$:new s.Subject,willStart$:new s.Subject,willResume$:new s.Subject,willPause$:new s.Subject,willStop$:new s.Subject,willDestruct$:new s.Subject,watchCoverageRecord$:new s.Subject,watchCoverageLive$:new s.Subject,managedError$:new s.Subject,fatalError$:new s.Subject,ended$:new s.Subject,looped$:new s.Subject,seeked$:new s.Subject,willSeek$:new s.Subject,firstBytes$:new s.Subject,firstFrame$:new s.Subject,canplay$:new s.Subject,log$:new s.Subject};experimental={element$:new s.ValueSubject(void 0),tuningConfigName$:new s.ValueSubject([]),enableDebugTelemetry$:new s.ValueSubject(!1),dumpTelemetry:gs};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=pr(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new dt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,r);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=mr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new hr({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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),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&&!Ut()?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(),r=this.info.isLive$.getValue();return e>=i&&!r&&(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 Sr(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 r=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.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:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||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({hasLiveOffsetByPaused:s.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(s.map(o=>o.to),s.filterChanged(),s.map(o=>o===exports.PlaybackState.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:o,isLowLatency:c})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),o){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(c));return}this.hasLiveOffsetByPaused.next(!1)})).add(s.combine({atLiveEdge:s.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ai({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(s.map(({isLive:o,position:c,isLowLatency:u})=>{const l=this.getActiveLiveDelay(u);return o&&Math.abs(c)<l/1e3}),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(s.map(({atLiveEdge:o,hasPausedTimeoutCase:c})=>o&&!c)).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(Ai({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 r=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?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),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$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),c=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue();let h;d===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:!u||!l?h=exports.Surface.NONE:o?h=exports.Surface.PIP:c?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(s.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new s.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(s.filterChanged((i,r)=>i.provider===r.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:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Dt(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),bs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ss(t)),this.providerContainer.current$.subscribe(({type:t})=>vt("provider",t)),e.duration$.subscribe(t=>vt("duration",t)),e.availableVideoTracks$.pipe(s.filter(t=>!!t.length),s.once()).subscribe(t=>vt("tracks",t)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(s.map(t=>t?.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(t=>this.subscription.add(t)),vt("codecs",nr())}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(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:s.ErrorCategory.DOM,message:String(r)})})};this.subscription.add(s.merge(s.fromEvent(document,"visibilitychange"),s.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;r&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const gr=`@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=br;exports.SDK_VERSION=gr;exports.VERSION=wi;