@vkontakte/videoplayer-core 2.0.98-dev.27a468df.0 → 2.0.98-dev.489417ae.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.98-dev.27a468df.0
3
- * Fri, 26 Jan 2024 03:19:31 GMT
2
+ * @vkontakte/videoplayer-core v2.0.98-dev.489417ae.0
3
+ * Thu, 15 Feb 2024 17:01:30 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
5
5
  */
6
- "use strict";var Ms=Object.create;var Ii=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Fs=Object.getOwnPropertyNames;var Os=Object.getPrototypeOf,Us=Object.prototype.hasOwnProperty;var Hs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fs(e))!Us.call(a,s)&&s!==t&&Ii(a,s,{get:()=>e[s],enumerable:!(i=Vs(e,s))||i.enumerable});return a};var Ni=(a,e,t)=>(t=a!=null?Ms(Os(a)):{},Hs(e||!a||!a.__esModule?Ii(t,"default",{value:a,enumerable:!0}):t,a));var r=require("@vkontakte/videoplayer-shared/esnext.cjs.js"),js=require("lodash/debounce.js"),Ys=require("lodash");const us="2.0.98-dev.27a468df.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",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 me;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(me||(me={}));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 V;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(V||(V={}));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 Gs=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 zs{connection$=new r.ValueSubject(void 0);castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new r.Subject;contentId;realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new r.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=r.isNonNullable(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},s||Gs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.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 r.assertNever(s.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),r.map(s=>s.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(qs),r.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const n=s===exports.ChromecastState.CONNECTED,o=r.isNonNullable(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();r.assertNonNullable(u);const d=u.getCastDevice(),c=u.getMediaSession()?.media.contentId;(r.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}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(s){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const qs=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 r.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 be=(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:r.assertNever(t)}return a};const si=(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:r.assertNever(e)}};var A=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class q{state;prevState;transition;transitionStarted$=new r.Subject;transitionEnded$=new r.Subject;transitionUpdated$=new r.Subject;forceChanged$=new r.Subject;stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=r.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||r.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 Ws=a=>{switch(a){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(a)}};var B;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(B||(B={}));const Qs=5,Js=5,Xs=500,_i=7e3;class Ks{subscription=new r.Subscription;loadMediaTimeoutSubscription=new r.Subscription;videoState=new q(B.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(Ws(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 r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(r.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new r.Subject;e.add(s.pipe(r.debounce(Xs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const u=o.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state===V.Applying||Math.abs(u-n)>Qs)&&s.next(u),n=u})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,u=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(u!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Js&&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:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(B.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:V.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PAUSED||e===B.PLAYING)&&(this.videoState.setState(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PLAYING||e===B.PAUSED)&&(this.videoState.setState(B.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===B.READY&&this.videoState.setState(B.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==B.STOPPED&&this.videoState.setState(B.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,s,n;switch(e){case exports.VideoFormat.MPEG:{const c=t[e];r.assertNonNullable(c);const h=r.getHighestQuality(Object.keys(c));r.assertNonNullable(h);const l=c[h];r.assertNonNullable(l),i=l,s="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=t[e];r.assertNonNullable(c),i=c.url,s="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 c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=be(c.url),s="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);o.contentUrl=i,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return r.isNonNullable(u)&&(o.metadata.title=u),r.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===V.Applying||i.state===V.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(_i).subscribe(()=>n(`timeout(${_i})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}).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(),s=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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.stop());return}if(!t){if(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&e!==B.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case B.PLAYING:case B.PAUSED:case B.READY:break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case B.PLAYING:break;case B.PAUSED:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.READY:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case B.PLAYING:this.videoState.startTransitionTo(B.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case B.PAUSED:break;case B.READY:this.videoState.startTransitionTo(B.PAUSED),this.videoState.setState(B.PAUSED);break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}default:r.assertNever(i)}}}}var Zs=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&e?.()}}},!0)},ea=a=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),s=new r.ValueSubject(void 0);let n=NaN,o=!1;const u=()=>{n=Date.now(),o=!1},d=h=>{const l=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in l||"x-playback-duration-millis"in l){const g=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??g*1e3??NaN;r.isNonNullable(b)&&!isNaN(b)&&e.next(b)}const f=l["x-delivery-type"]??exports.HttpConnectionType.HTTP1,p={1:!0,0:!1}[l["x-reused"]]??void 0;i.next(f),s.next(p)},c=h=>{h.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return a.extend("XHRLoader",function(){const{parent:h}=this,l=h.load.bind(h);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,g=f.progress;f.onload=function(...y){return d(this),p(...y)},f.progress=function(...y){return c(this),g(...y)},u()}return l(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},ct=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},ta=a=>a.extend("RequestModifier",()=>({modifyRequestURL:ct}),!0),ia=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,n]=i.request.range.split("-").map(u=>parseInt(u,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Ve=(a,e,t,{equal:i=(o,u)=>o===u,changed$:s,onError:n}={})=>{const o=a.getState(),u=e(),d=r.isNullable(s),c=new r.Subscription;return s&&c.add(s.subscribe(h=>{const l=a.getState();i(h,l)&&a.setState(h)},n)),i(u,o)||(t(o),d&&a.setState(o)),c.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),d&&a.setState(h.to)},n)),c},dt=(a,e,t)=>Ve(e,()=>a.loop,i=>{r.isNonNullable(i)&&(a.loop=i)},{onError:t}),Qe=(a,e,t,i)=>Ve(e,()=>({muted:a.muted,volume:a.volume}),s=>{r.isNonNullable(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,n)=>s===n||s?.muted===n?.muted&&s?.volume===n?.volume,changed$:t,onError:i}),rt=(a,e,t,i)=>Ve(e,()=>a.playbackRate,s=>{r.isNonNullable(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),sa=a=>["__",a.language,a.label].join("|"),aa=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class Fe{available$=new r.Subject;current$=new r.ValueSubject(void 0);error$=new r.Subject;video;cueSettings;subscription=new r.Subscription;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:r.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(Ve(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Ve(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ve(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:s})),this.subscription.add(Ve(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,s)=>i.length===s.length&&i.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(r.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 s=i;r.isNonNullable(t.align)&&(s.align=t.align),r.isNonNullable(t.position)&&(s.position=t.position),r.isNonNullable(t.size)&&(s.size=t.size),r.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Fe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:sa(e),n=this.externalTracks.has(s),o=s.includes("auto");return n?{id:s,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(s)?.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:s,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===s&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!aa(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){r.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){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Di=a=>{a.removeAttribute("src"),a.load()},ra=a=>{try{a.pause(),a.playbackRate=0,Di(a),a.remove()}catch(e){console.error(e)}};class na{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 vi=window.WeakMap?new WeakMap:new na,Je=a=>{let e=a.querySelector("video");const t=!!e;return e?Di(e):(e=document.createElement("video"),a.appendChild(e)),vi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Xe=a=>{const e=vi.get(a);vi.delete(a),e?Di(a):ra(a)};class Wt{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 cs=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Bi=a=>{const e=cs(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},oa=a=>{const e=cs(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ei=3;class ua{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Ei&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ei))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,u=n>=e&&n<t;o&&u||(o?i(t,n):u?i(s,e):s<e&&n>t?(i(t,n),i(s,e)):i(s,n))})}destroy(){this._buffer=[]}}var ds=(a,e,t=Ei)=>{let i=0,s=0;for(let n=0;n<a.length;n++){const o=a.start(n),u=a.end(n);if(o<=e&&e<=u){if(i=o,s=u,!t)return{from:i,to:s};for(let d=n-1;d>=0;d--)a.end(d)+t>=i&&(i=a.start(d));for(let d=n+1;d<a.length;d++)a.start(d)-t<=s&&(s=a.end(d))}}return{from:i,to:s}};const Ke=a=>{const e=m=>r.fromEvent(a,m).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(m=>r.fromEvent(a,m))).pipe(r.map(m=>m.type==="ended"?a.readyState<2:a.readyState<3),r.filterChanged()),s=r.merge(r.fromEvent(a,"progress"),r.fromEvent(a,"timeupdate")).pipe(r.map(()=>ds(a.buffered,a.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),u=r.fromEvent(a,"volumechange").pipe(r.map(()=>({muted:a.muted,volume:a.volume}))),d=r.fromEvent(a,"ratechange").pipe(r.map(()=>a.playbackRate)),c=r.fromEvent(a,"error").pipe(r.filter(()=>!!(a.error||a.played.length)),r.map(()=>{const m=a.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=r.fromEvent(a,"timeupdate").pipe(r.map(()=>a.currentTime)),l=new r.Subject,f=.3;let p;h.subscribe(m=>{a.loop&&r.isNonNullable(p)&&r.isNonNullable(m)&&p>=a.duration-f&&m<=f&&l.next(p),p=m});const g=r.fromEvent(a,"enterpictureinpicture"),y=r.fromEvent(a,"leavepictureinpicture"),b=new r.ValueSubject(oa(a));g.subscribe(()=>b.next(!0)),y.subscribe(()=>b.next(!1));const k=new r.ValueSubject(Bi(a));return r.fromEvent(a,"fullscreenchange").pipe(r.map(()=>Bi(a))).subscribe(k),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:r.fromEvent(a,"durationchange").pipe(r.map(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:u,playbackRateState$:d,inPiP$:b,inFullscreen$:k}},mi=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let Ci=!1,st={};const ca=a=>{Ci=a},da=()=>{st={}},la=a=>{a(st)},Kt=(a,e)=>{Ci&&(st.meta=st.meta??{},st.meta[a]=e)};class Ge{name;constructor(e){this.name=e}next(e){if(!Ci)return;st.series=st.series??{};const t=st.series[this.name]??[];t.push([Date.now(),e]),st.series[this.name]=t}}var gt;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(gt||(gt={}));const ha=new Ge("best_bitrate"),fa=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class ls{last;history={};recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const pa='Assertion "ABR Tracks is empty array" failed',Tt=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:c,droppedVideoMaxQualityLimit:h,abrLogger:l})=>{r.assertNotEmptyArray(a,pa);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},g=p&&r.videoSizeToQuality(p),y=i.considerPlaybackRate&&r.isNonNullable(u)?u:1,b=a.filter(S=>!r.isInvariantQuality(S.quality)).sort((S,L)=>r.isHigher(S.quality,L.quality)?-1:1),k=b.at(-1)?.quality,w=b.at(0)?.quality,m=r.isNullable(s)||r.isNonNullable(s.min)&&r.isNonNullable(s.max)&&r.isLower(s.max,s.min)||r.isNonNullable(s.min)&&w&&r.isHigher(s.min,w)||r.isNonNullable(s.max)&&k&&r.isLower(s.max,k),E=y*fa(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},_=b.filter(S=>(g?r.isLower(S.quality,g):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(S.bitrate)?t-n>=S.bitrate*E:!0)?i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!r.isInvariantQuality(d.quality)&&(o??0)<i.minBufferToSwitchUp&&r.isHigher(S.quality,d.quality)?($[S.quality]=gt.Buffer,!1):!!h&&r.isHigherOrEqual(S.quality,h)?($[S.quality]=gt.DroppedFramesLimit,!1):m||(r.isNullable(s.max)||r.isLowerOrEqual(S.quality,s.max))&&(r.isNullable(s.min)||r.isHigherOrEqual(S.quality,s.min))?!0:($[S.quality]=gt.FitsQualityLimits,!1):($[S.quality]=gt.FitsThroughput,!1):($[S.quality]=gt.FitsContainer,!1))[0];_&&_.bitrate&&ha.next(_.bitrate);const C=_??b[Math.ceil((b.length-1)/2)]??a[0];C.quality!==c?.last?.quality&&l({message:`
6
+ "use strict";var Ms=Object.create;var Ii=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Fs=Object.getOwnPropertyNames;var Os=Object.getPrototypeOf,Us=Object.prototype.hasOwnProperty;var Hs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fs(e))!Us.call(a,s)&&s!==t&&Ii(a,s,{get:()=>e[s],enumerable:!(i=Vs(e,s))||i.enumerable});return a};var Ni=(a,e,t)=>(t=a!=null?Ms(Os(a)):{},Hs(e||!a||!a.__esModule?Ii(t,"default",{value:a,enumerable:!0}):t,a));var r=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const us="2.0.98-dev.489417ae.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",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 ge;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ge||(ge={}));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 V;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(V||(V={}));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 js=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 Ys{connection$=new r.ValueSubject(void 0);castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new r.Subject;contentId;realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new r.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=r.isNonNullable(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},s||js("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.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 r.assertNever(s.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),r.map(s=>s.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(Gs),r.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const n=s===exports.ChromecastState.CONNECTED,o=r.isNonNullable(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();r.assertNonNullable(u);const d=u.getCastDevice(),c=u.getMediaSession()?.media.contentId;(r.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}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(s){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Gs=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 r.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 Se=(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:r.assertNever(t)}return a};const si=(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:r.assertNever(e)}};var w=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class q{state;prevState;transition;transitionStarted$=new r.Subject;transitionEnded$=new r.Subject;transitionUpdated$=new r.Subject;forceChanged$=new r.Subject;stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=r.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||r.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 zs=a=>{switch(a){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(a)}};var B;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(B||(B={}));const qs=5,Ws=5,Qs=500,_i=7e3;class Js{subscription=new r.Subscription;loadMediaTimeoutSubscription=new r.Subscription;videoState=new q(B.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(zs(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(r.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new r.Subject;e.add(s.pipe(r.debounce(Qs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const u=o.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state===V.Applying||Math.abs(u-n)>qs)&&s.next(u),n=u})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,u=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(u!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Ws&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(B.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:V.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PAUSED||e===B.PLAYING)&&(this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PLAYING||e===B.PAUSED)&&(this.videoState.setState(B.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===B.READY&&this.videoState.setState(B.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==B.STOPPED&&this.videoState.setState(B.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,s,n;switch(e){case exports.VideoFormat.MPEG:{const c=t[e];r.assertNonNullable(c);const h=r.getHighestQuality(Object.keys(c));r.assertNonNullable(h);const l=c[h];r.assertNonNullable(l),i=l,s="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=t[e];r.assertNonNullable(c),i=c.url,s="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 c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=Se(c.url),s="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);o.contentUrl=i,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return r.isNonNullable(u)&&(o.metadata.title=u),r.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===V.Applying||i.state===V.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(_i).subscribe(()=>n(`timeout(${_i})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}).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(),s=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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.stop());return}if(!t){if(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&e!==B.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case B.PLAYING:case B.PAUSED:case B.READY:break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case B.PLAYING:break;case B.PAUSED:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.READY:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case B.PLAYING:this.videoState.startTransitionTo(B.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case B.PAUSED:break;case B.READY:this.videoState.startTransitionTo(B.PAUSED),this.videoState.setState(B.PAUSED);break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}default:r.assertNever(i)}}}}var Xs=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&e?.()}}},!0)},Ks=a=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),s=new r.ValueSubject(void 0);let n=NaN,o=!1;const u=()=>{n=Date.now(),o=!1},d=h=>{const l=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in l||"x-playback-duration-millis"in l){const g=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??g*1e3??NaN;r.isNonNullable(b)&&!isNaN(b)&&e.next(b)}const f=l["x-delivery-type"]??exports.HttpConnectionType.HTTP1,p={1:!0,0:!1}[l["x-reused"]]??void 0;i.next(f),s.next(p)},c=h=>{h.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return a.extend("XHRLoader",function(){const{parent:h}=this,l=h.load.bind(h);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,g=f.progress;f.onload=function(...y){return d(this),p(...y)},f.progress=function(...y){return c(this),g(...y)},u()}return l(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},ct=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Zs=a=>a.extend("RequestModifier",()=>({modifyRequestURL:ct}),!0),ea=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,n]=i.request.range.split("-").map(u=>parseInt(u,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Ve=(a,e,t,{equal:i=(o,u)=>o===u,changed$:s,onError:n}={})=>{const o=a.getState(),u=e(),d=r.isNullable(s),c=new r.Subscription;return s&&c.add(s.subscribe(h=>{const l=a.getState();i(h,l)&&a.setState(h)},n)),i(u,o)||(t(o),d&&a.setState(o)),c.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),d&&a.setState(h.to)},n)),c},dt=(a,e,t)=>Ve(e,()=>a.loop,i=>{r.isNonNullable(i)&&(a.loop=i)},{onError:t}),Qe=(a,e,t,i)=>Ve(e,()=>({muted:a.muted,volume:a.volume}),s=>{r.isNonNullable(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,n)=>s===n||s?.muted===n?.muted&&s?.volume===n?.volume,changed$:t,onError:i}),rt=(a,e,t,i)=>Ve(e,()=>a.playbackRate,s=>{r.isNonNullable(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),ta=a=>["__",a.language,a.label].join("|"),ia=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class Fe{available$=new r.Subject;current$=new r.ValueSubject(void 0);error$=new r.Subject;video;cueSettings;subscription=new r.Subscription;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:r.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(Ve(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Ve(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ve(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:s})),this.subscription.add(Ve(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,s)=>i.length===s.length&&i.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(r.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 s=i;r.isNonNullable(t.align)&&(s.align=t.align),r.isNonNullable(t.position)&&(s.position=t.position),r.isNonNullable(t.size)&&(s.size=t.size),r.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Fe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:ta(e),n=this.externalTracks.has(s),o=s.includes("auto");return n?{id:s,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(s)?.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:s,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===s&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!ia(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){r.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){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Di=a=>{a.removeAttribute("src"),a.load()},sa=a=>{try{a.pause(),a.playbackRate=0,Di(a),a.remove()}catch(e){console.error(e)}};class aa{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 vi=window.WeakMap?new WeakMap:new aa,Je=a=>{let e=a.querySelector("video");const t=!!e;return e?Di(e):(e=document.createElement("video"),a.appendChild(e)),vi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Xe=a=>{const e=vi.get(a);vi.delete(a),e?Di(a):sa(a)};class Wt{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 cs=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Bi=a=>{const e=cs(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ra=a=>{const e=cs(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ei=3;class na{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Ei&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ei))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,u=n>=e&&n<t;o&&u||(o?i(t,n):u?i(s,e):s<e&&n>t?(i(t,n),i(s,e)):i(s,n))})}destroy(){this._buffer=[]}}var ds=(a,e,t=Ei)=>{let i=0,s=0;for(let n=0;n<a.length;n++){const o=a.start(n),u=a.end(n);if(o<=e&&e<=u){if(i=o,s=u,!t)return{from:i,to:s};for(let d=n-1;d>=0;d--)a.end(d)+t>=i&&(i=a.start(d));for(let d=n+1;d<a.length;d++)a.start(d)-t<=s&&(s=a.end(d))}}return{from:i,to:s}};const Ke=a=>{const e=m=>r.fromEvent(a,m).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(m=>r.fromEvent(a,m))).pipe(r.map(m=>m.type==="ended"?a.readyState<2:a.readyState<3),r.filterChanged()),s=r.merge(r.fromEvent(a,"progress"),r.fromEvent(a,"timeupdate")).pipe(r.map(()=>ds(a.buffered,a.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),u=r.fromEvent(a,"volumechange").pipe(r.map(()=>({muted:a.muted,volume:a.volume}))),d=r.fromEvent(a,"ratechange").pipe(r.map(()=>a.playbackRate)),c=r.fromEvent(a,"error").pipe(r.filter(()=>!!(a.error||a.played.length)),r.map(()=>{const m=a.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=r.fromEvent(a,"timeupdate").pipe(r.map(()=>a.currentTime)),l=new r.Subject,f=.3;let p;h.subscribe(m=>{a.loop&&r.isNonNullable(p)&&r.isNonNullable(m)&&p>=a.duration-f&&m<=f&&l.next(p),p=m});const g=r.fromEvent(a,"enterpictureinpicture"),y=r.fromEvent(a,"leavepictureinpicture"),b=new r.ValueSubject(ra(a));g.subscribe(()=>b.next(!0)),y.subscribe(()=>b.next(!1));const k=new r.ValueSubject(Bi(a));return r.fromEvent(a,"fullscreenchange").pipe(r.map(()=>Bi(a))).subscribe(k),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:r.fromEvent(a,"durationchange").pipe(r.map(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:u,playbackRateState$:d,inPiP$:b,inFullscreen$:k}},mi=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let Ci=!1,st={};const oa=a=>{Ci=a},ua=()=>{st={}},ca=a=>{a(st)},Kt=(a,e)=>{Ci&&(st.meta=st.meta??{},st.meta[a]=e)};class Ge{name;constructor(e){this.name=e}next(e){if(!Ci)return;st.series=st.series??{};const t=st.series[this.name]??[];t.push([Date.now(),e]),st.series[this.name]=t}}var gt;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(gt||(gt={}));const da=new Ge("best_bitrate"),la=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class ls{last;history={};recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ha='Assertion "ABR Tracks is empty array" failed',Tt=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:c,droppedVideoMaxQualityLimit:h,abrLogger:l})=>{r.assertNotEmptyArray(a,ha);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},g=p&&r.videoSizeToQuality(p),y=i.considerPlaybackRate&&r.isNonNullable(u)?u:1,b=a.filter(S=>!r.isInvariantQuality(S.quality)).sort((S,L)=>r.isHigher(S.quality,L.quality)?-1:1),k=b.at(-1)?.quality,A=b.at(0)?.quality,m=r.isNullable(s)||r.isNonNullable(s.min)&&r.isNonNullable(s.max)&&r.isLower(s.max,s.min)||r.isNonNullable(s.min)&&A&&r.isHigher(s.min,A)||r.isNonNullable(s.max)&&k&&r.isLower(s.max,k),T=y*la(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},_=b.filter(S=>(g?r.isLower(S.quality,g):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(S.bitrate)?t-n>=S.bitrate*T:!0)?i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!r.isInvariantQuality(d.quality)&&(o??0)<i.minBufferToSwitchUp&&r.isHigher(S.quality,d.quality)?($[S.quality]=gt.Buffer,!1):!!h&&r.isHigherOrEqual(S.quality,h)?($[S.quality]=gt.DroppedFramesLimit,!1):m||(r.isNullable(s.max)||r.isLowerOrEqual(S.quality,s.max))&&(r.isNullable(s.min)||r.isHigherOrEqual(S.quality,s.min))?!0:($[S.quality]=gt.FitsQualityLimits,!1):($[S.quality]=gt.FitsThroughput,!1):($[S.quality]=gt.FitsContainer,!1))[0];_&&_.bitrate&&da.next(_.bitrate);const C=_??b[Math.ceil((b.length-1)/2)]??a[0];C.quality!==c?.last?.quality&&l({message:`
7
7
  [available tracks]
8
8
  ${a.map(S=>`{ id: ${S.id}, quality: ${S.quality}, bitrate: ${S.bitrate} }`).join(`
9
9
  `)}
@@ -19,7 +19,7 @@
19
19
  playbackRate: ${u},
20
20
  playbackRateFactor: ${y},
21
21
  forwardBufferHealth: ${o},
22
- bitrateFactor: ${E},
22
+ bitrateFactor: ${T},
23
23
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
24
24
  droppedVideoMaxQualityLimit: ${h},
25
25
  limitsAreInvalid: ${m},
@@ -34,13 +34,13 @@
34
34
  [selected track] ${C?.quality}
35
35
  `});const I=C&&c&&c.history[C.id]&&r.now()-c.history[C.id]<=i.trackCooldown&&(!c.last||C.id!==c.last.id);if(C?.id&&c&&!I&&c.recordSelection(C),I&&c?.last){const S=c.last;return c?.recordSwitch(S),l({message:`
36
36
  [last selected] ${S?.quality}
37
- `}),S}return c?.recordSwitch(C),C};var Se=a=>new URL(a).hostname;const ma=300,zt=(a,e=ma)=>new r.Observable(t=>{const{width:i,height:s}=a.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(js(o=>{const u=o[0];if(!u)return;let d,c;u.contentBoxSize&&u.contentBoxSize[0]?(c=u.contentBoxSize[0].blockSize,d=u.contentBoxSize[0].inlineSize):u.contentRect&&(d=u.contentRect.width,c=u.contentRect.height),r.isNonNullable(d)&&r.isNonNullable(c)&&t.next({width:d,height:c})},e));return n.observe(a),()=>n.disconnect()});class Qt{onDroopedVideoFramesLimit$=new r.Subject;subscription=new r.Subscription;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new r.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(r.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=r.interval(this.droppedFramesChecker.checkTime).pipe(r.filter(()=>this.playing),r.filter(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(r.debounce(this.droppedFramesChecker.checkTime)),i=r.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&&!r.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,s=t-this.prevDroppedVideoFrames,n=1-(i-s)/i;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&r.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],[s])=>r.isLower(i,s)?-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 Mt={};var O;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(O||(O={}));const re=(a,e)=>new r.Observable(t=>{const i=s=>t.next(s);return a.on(e,i),()=>a.off(e,i)});class Mi{subscription=new r.Subscription;videoState=new q(O.DOWNLOADING_LIB);video;player;params;textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);frameRatesByFrameHeight={};isLive$=new r.ValueSubject(void 0);maxSeekBackTime$=new r.ValueSubject(1/0);availableFrom$=new r.ValueSubject(void 0);elementSize$=new r.ValueSubject(void 0);liveOffset=new Wt;constructor(e){this.video=Je(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${s?.toString?.()}`,thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Mt.MediaPlayer=s.MediaPlayer,Mt.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Mt.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Mt.Debug,"dashjs not loaded"),this.player=Mt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?mi(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&ia(this.player),Zs(this.player),this.params.tuning.requestQuick&&ta(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(O.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,E)=>this.subscription.add(m.subscribe(E,i));s(zt(this.video),this.elementSize$),s(re(this.player,"error").pipe(r.map(m=>{const E=typeof m.error=="object"?m.error.code:m.error,$=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${E}`,message:$}})),e.error$),s(re(this.player,"playbackError").pipe(r.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({newQuality:m})=>this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===m)?.track));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:m})=>m===O.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(Ve(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===m)?.track},m=>{if(r.isNullable(m))return;const E=this.videoTracks$.getValue().find(({track:$})=>$.id===m.id)?.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n,onError:i}))},i)),this.subscription.add(Ve(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),s(re(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:E}})=>{const $=this.player.getDashMetrics(),R=$.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),_=$.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??exports.HttpConnectionType.HTTP1,C={1:!0,0:!1}[R]??void 0;this.params.output.httpConnectionType$.next(_),this.params.output.httpConnectionReused$.next(C),e.hostname$.next(Se(E))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:E,availableFrom:$}}})=>{this.isLive$.next(E),this.availableFrom$.next($.getTime()),E||e.duration$.next(m);const R=[],_=this.player.getQualityFor("video");let C;for(const I of this.player.getBitrateInfoListFor("video")){const S=I.qualityIndex.toString(10),L=r.videoSizeToQuality(I),N=I.bitrate/1e3,j={width:I.width,height:I.height},ie=this.frameRatesByFrameHeight[I.height];if(L){const ne={id:S,quality:L,bitrate:N,size:j,fps:ie};R.push({track:ne,bitrateInfo:I}),I.qualityIndex===_&&(C=ne)}}this.videoTracks$.next(R),e.availableVideoTracks$.next(R.map(({track:I})=>I)),C&&e.currentVideoTrack$.next(C),this.videoState.setState(O.STREAM_INITIALIZED),this.videoState.startTransitionTo(O.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const E=m.requestEndDate.getTime()-m.firstByteDate.getTime(),$=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,E)}),s(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),E=Tt(this.videoTracks$.getValue().map(({track:_})=>_),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),$=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to);const R=this.videoTracks$.getValue().find(({track:_})=>_===E);R?.bitrateInfo&&this.player.setQualityFor("video",R?.bitrateInfo.qualityIndex,!1)}),s(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:m})=>m),r.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(r.map(({time:m})=>m??0));s(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:E})=>this.params.output.liveTime$.next(m+E*1e3)),s(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(r.map(()=>ds(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(O.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(O.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(O.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===O.READY&&this.videoState.setState(O.READY)}),s(this.isLive$,e.isLive$),s(zt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const u=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));s(u,this.syncPlayback);const{playbackDuration$:d,ping$:c,connectionType$:h,connectionReused$:l}=ea(this.player);s(h,this.params.output.httpConnectionType$),s(l,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(c.pipe(r.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(m=>m<60))}),({isLive:m,isShort:E})=>{const $=!m&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),s(o.pipe(r.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(re(this.player,"manifestLoaded"),m=>{if(m.data?.Period?.AdaptationSet){const E=[];for(const $ of m.data?.Period?.AdaptationSet)if($.contentType==="text"){const R=$.Representation?.id,_=new URL($.Representation?.BaseURL,m.data?.baseUri).toString(),C="internal",I=$.lang;E.push({id:R,url:_,type:C,language:I})}t.internalTextTracks.startTransitionTo(E)}}),this.subscription.add(dt(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:g,inPiP$:y,inFullscreen$:b,pause$:k,playing$:w}=Ke(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:w,pause$:k,tracks$:this.videoTracks$.pipe(r.map(m=>m.map(({track:E})=>E)))}),this.subscription.add(Qe(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(rt(this.video,t.playbackRate,g,i)),this.subscription.add(y.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(O.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(O.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=be(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,X.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(O.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(O.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===O.DOWNLOADING_LIB||e===O.STREAM_INITIALIZED))switch(i?.to!==exports.PlaybackState.PAUSED&&s.state===V.Requested&&e!==O.STOPPED&&t!==exports.PlaybackState.STOPPED&&(n?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case exports.PlaybackState.STOPPED:{switch(e){case O.STOPPED:break;case O.PLAYING:case O.PAUSED:case O.READY:this.stop();break;default:r.assertNever(e)}break}case exports.PlaybackState.READY:{switch(e){case O.STOPPED:this.prepare();break;case O.PLAYING:case O.PAUSED:case O.READY:break;default:r.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case O.PLAYING:break;case O.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case O.READY:this.play();break;case O.STOPPED:this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case O.PLAYING:this.pause(),this.liveOffset.pause();break;case O.PAUSED:break;case O.READY:this.videoState.setState(O.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case O.STOPPED:this.prepare();break;default:r.assertNever(e)}break}default:r.assertNever(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}Xe(this.video),this.params.output.element$.next(void 0)}}var It=a=>{switch(a){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}};const Vi=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 nt=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!Vi(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return Vi(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function ge(){return r.now()}function hs(a){return ge()-a}function Fi(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=o=>i.test(o);return{resolve:(o,u,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let c=o.indexOf("?")>-1?"&":"?";return d&&(o+=c+"lowLat=1",c="&"),u&&(o+=c+"_rnd="+Math.floor(999999999*Math.random())),o}}}function ga(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function ii(a,e,t,i){const s=window.XMLHttpRequest;let n,o,u,d=!1,c=0,h,l,f=!1,p="arraybuffer",g=7e3,y=2e3,b=()=>{if(d)return;r.assertNonNullable(h);const N=hs(h);let j;if(N<y){j=y-N,setTimeout(b,j);return}y*=2,y>g&&(y=g),o&&o.abort(),o=new s,R()};const k=N=>(n=N,L),w=N=>(l=N,L),m=()=>(p="json",L),E=()=>{if(!d){if(--c>=0){b(),i&&i();return}d=!0,l&&l(),t&&t()}},$=N=>(f=N,L),R=()=>{h=ge(),o=new s,o.open("get",a);let N=0,j,ie=0;const ne=()=>(r.assertNonNullable(h),Math.max(h,Math.max(j||0,ie||0)));if(n&&o.addEventListener("progress",x=>{const G=ge();n.updateChunk&&x.loaded>N&&(n.updateChunk(ne(),x.loaded-N),N=x.loaded,j=G)}),u&&(o.timeout=u,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const x=o.status;if(x>=200&&x<300){if(o.response.byteLength&&n){const G=o.response.byteLength-N;G&&n.updateChunk&&n.updateChunk(ne(),G)}l&&l(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const x=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ie=ge(),o.removeEventListener("readystatechange",x))};o.addEventListener("readystatechange",x)}return o.responseType=p,o.send(),L},L={withBitrateReporting:k,withParallel:$,withJSONResponse:m,withRetryCount:N=>(c=N,L),withRetryInterval:(N,j)=>(r.isNonNullable(N)&&(y=N),r.isNonNullable(j)&&(g=j),L),withTimeout:N=>(u=N,L),withFinally:w,send:R,abort:()=>{o&&(o.abort(),o=void 0),d=!0,l&&l()}};return L}const ba=100,Sa=2e3,ya=500;let Ta=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-ya;if(t-e>Sa){let i=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,u=n.end-n.start;i+=o;const d=n.bytes*o/u;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&i>0){const n=s*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(s)}/${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>ba&&(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 va{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,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=ge(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=ge()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ii(t,n,()=>s("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ge()}_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=ge();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,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=s,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 u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=i,n._retryCB=s,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 Zt=1e4,ei=3,Ea=300,ka=2e3,$a=6e4,Aa=10,wa=1,Pa=500;class Da{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 Ta(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Fi(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=Fi(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 s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u)n=this.manifest[u],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!i||i.bitrate>n.bitrate)&&(i=n));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{ga(s,"progress",()=>{s.buffered.length?(s.currentTime=s.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 va(ei,Zt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let n=!1,o=null,u=null,d=null,c=null,h=!1;const l=()=>{const E=n&&(!h||h===this.rep);return E||t("Not running!"),E},f=(E,$,R)=>{d&&d.abort(),d=ii(this.urlResolver.resolve(E,!1),$,R,()=>this._retryCallback()).withTimeout(Zt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ei).withFinally(()=>{d=null}).send()},p=(E,$,R)=>{r.assertNonNullable(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,R,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},g=E=>{const $=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),i.playbackRate=E)},y=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)g(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){g(1);return}const R=ge()-1e4;let _=0;for(let I=0;I<this.bufferStates.length;I++){const S=this.bufferStates[I];E=Math.min(E,S.buf),S.ts<R&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${E} drop=${_} jitter=${this.sourceJitter}`);let C=E-wa;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?g(1.15):C>1?g(1.1):C>.3?g(1.05):g(1)}},k=E=>{let $;const R=()=>$&&$.start?$.start.length:0,_=x=>$.start[x]/1e3,C=x=>$.dur[x]/1e3,I=x=>$.fragIndex+x,S=(x,G)=>({chunkIdx:I(x),startTS:_(x),dur:C(x),discontinuity:G}),L=()=>{let x=0;if($&&$.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,oe=G;this.sourceJitter>1&&(oe+=this.sourceJitter-1);let pe=$.dur.length-1;for(;pe>=0&&(oe-=$.dur[pe],!(oe<=0));--pe);x=Math.min(pe,$.dur.length-1-K),x=Math.max(x,0)}return S(x,!0)},N=x=>{const G=R();if(!(G<=0)){if(r.isNonNullable(x)){for(let K=0;K<G;K++)if(_(K)>x)return S(K)}return L()}},j=x=>{const G=R(),K=x?x.chunkIdx+1:0,oe=K-$.fragIndex;if(!(G<=0)){if(!x||oe<0||oe-G>Aa)return t(`Resync: offset=${oe} bChunks=${G} chunk=`+JSON.stringify(x)),L();if(!(oe>=G))return S(K-$.fragIndex,!1)}},ie=(x,G,K)=>{c&&c.abort(),c=ii(this.urlResolver.resolve(x,!0,this.lowLatency),G,K,()=>this._retryCallback()).withTimeout(Zt).withRetryCount(ei).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,G)=>{ie(E,K=>{if(!l())return;$=K;const oe=!!$.lowLatency;oe!==this.lowLatency&&y(oe);let pe=0;for(let Oe=0;Oe<$.dur.length;++Oe)pe+=$.dur[Oe];pe>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(pe/$.dur.length)),s({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,x(N(G))},()=>this._handleNetworkError())},nextChunk:j}},w=()=>{n=!1,u&&u.abort(),d&&d.abort(),c&&c.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:E=>{const{videoElement:$,logger:R}=this.params;let _=k(e.jidxUrl),C,I,S,L,N=0,j,ie,ne;const x=()=>{j&&(clearTimeout(j),j=void 0);const z=Math.max(Pa,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=N+z,ye=ge(),de=Math.min(1e4,ce-ye);N=ye;const et=()=>{c||l()&&_.seek(()=>{l()&&(N=ge(),G(),x())})};de>0?j=window.setTimeout(()=>{this.paused?x():et()},de):et()},G=()=>{let z;for(;z=_.nextChunk(L);)L=z,_t(z);const ce=_.nextChunk(S);if(ce){if(S&&ce.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(w(),this._initPlayerWith(e));return}Oe(ce)}else x()},K=(z,ce)=>{if(!l()||!this.sourceBuffer)return;let ye,de,et;const se=ke=>{window.setTimeout(()=>{l()&&K(z,ce)},ke)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),se(100);else{const ke=ge(),ue=$.currentTime;!this.paused&&$.buffered.length>1&&ie===ue&&ke-ne>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ie!==ue&&(ie=ue,ne=ke);const le=this._getBufferSizeSec();if(le>30)R(`Buffered ${le} seconds; delaying appendBuffer`),se(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:ke,buf:le}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(Ue){if(Ue.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),et=this.sourceBuffer.buffered.length,et!==0&&(ye=this.sourceBuffer.buffered.start(0),de=ue,de-ye>4&&this.sourceBuffer.remove(ye,de-3)),se(1e3);else throw Ue}}},oe=()=>{I&&C&&(R([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(S)]),K(I,function(){I=null,G()}))},pe=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Oe=z=>{l()&&p(pe(z),(ce,ye)=>{if(l()){if(ye/=1e3,I=ce,S=z,o=z.startTS,ye){const de=Math.min(10,z.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*de:de}oe()}},()=>this._handleNetworkError())},_t=z=>{l()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(pe(z),!1)))},vt=z=>{l()&&(e.cachedHeader=z,K(z,()=>{C=!0,oe()}))};n=!0,_.seek(z=>{if(l()){if(N=ge(),!z){x();return}L=z,!r.isNullable(E)||z.startTS>E?Oe(z):(S=z,G())}},E),e.cachedHeader?vt(e.cachedHeader):f(e.headerUrl,vt,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>o},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),r.isNonNullable(s)&&(s+=.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,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let f,p,g;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(p=this._getBufferSizeSec(),g=l/this.bitrate,p>10&&g>.8||p>15&&g>.5||p>20&&g>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}f=this._selectQuality(l),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${l}`)},n=(()=>({updateChunk:(f,p)=>{const g=ge();if(this.chunkRateEstimator.addInterval(f,g,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:g-f,speed:b}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,u,d=!0;const c=()=>{let l=n.get();if(l&&u&&this.autoQuality){if(d&&l>u&&hs(o)<3e4)return;i(l)}d=this.autoQuality};return{updateChunk:(l,f)=>{const p=n.updateChunk(l,f);return p&&c(),p},notifySwitch:l=>{const f=ge();l<u&&(o=f),u=l}}}_fetchManifest(e,t,i){this.manifestRequest=ii(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Zt).withRetryCount(ei).withRetryInterval(Ea,ka).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;nt(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,n=o=>{const u=[];return o?.length?(o.forEach((d,c)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=c,u.push(d))}),u.sort(function(d,c){return d.video&&c.video?c.video.height-d.video.height:c.bitrate-d.bitrate}),u):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),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))},$a))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var F;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(F||(F={}));const Ca=[F.PAUSED,F.PLAYING,F.READY],La=[F.PAUSED,F.PLAYING,F.READY];class xa{subscription=new r.Subscription;video;videoState=new q(F.STOPPED);dash;representations$=new r.ValueSubject([]);textTracksManager=new Fe;droppedFramesManager=new Qt;maxSeekBackTime$=new r.ValueSubject(1/0);zeroTime$=new r.ValueSubject(void 0);liveOffset=new Wt;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Je(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(Se(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=Ke(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(r.map(s=>s.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===F.READY&&this.videoState.setState(F.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(F.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(Qe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(rt(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:s}})=>{const n=s&&r.videoQualityToHeight(s);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case F.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case F.MANIFEST_READY:case F.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case F.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case F.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(s.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}createLiveDashPlayer(){const e=new Da({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&r.isNonNullable(t)?t:Tt(e.map(({track:c})=>c),{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=s?.id,o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(o||n!==u)&&this.setVideoTrack(s),d&&this.setAutoQuality(i),o||d||n!==u){const c=e.find(({track:h})=>h.id===n)?.representation;r.assertNonNullable(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;r.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(),s=t===exports.PlaybackState.PAUSED&&i===F.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(be(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const n=s.name??s.index.toString(10),o=It(s.name)??r.videoSizeToQuality(s.video),u=s.bitrate/1e3,d={...s.video};if(!o)continue;const c={id:n,quality:o,bitrate:u,size:d};i.push({track:c,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===F.MANIFEST_READY&&this.videoState.setState(F.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),r.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(),s=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!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(F.STOPPED));return}if(t)return;const o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(La.includes(e)&&(o||u)){this.prepare();return}if(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&Ca.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_READY),this.dash.attachSource(be(this.params.source.url));return;case F.MANIFEST_READY:this.videoState.startTransitionTo(F.READY),this.prepare();break;case F.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(F.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(F.PLAYING);const d=s?.from;d&&d===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(F.PAUSED)})}return;case F.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(F.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case F.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(F.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(F.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(be(this.params.source.url,d))}return;default:return r.assertNever(e)}}}var Li=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?exports.HttpConnectionType.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},Ee=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,n=a.end(i)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Ra=a=>{const e=document.createElement("a");return e.href=a,e.origin},Ia=a=>{const e=document.createElement("a");return e.href=a,e.host};class fs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,n,o){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(this._xhr){if(this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(i=>i.split(":").map(s=>s.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(Ia(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",t,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class ai{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,u=s.length;o<u;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,n,o,u){this.abort(()=>{let d=0;const c=Date.now();let h=0,l=0,f=0;const p=y=>{s(ai._str2ua(y.substr(d))),d=y.length};let g=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(g=ct(g)),this._lastXhr=new fs(g,e.failoverHosts,y=>{this._lastXhr=void 0,p(y);const b=Date.now()-c;this._params.onBandwidthChange({size:y.length,duration:b,speed:8*y.length/(b/1e3)}),this._onDashCallback("loading",{size:y.length,done:!0}),n?.()},y=>{if(y.length-d>u&&p(y),l===0){l=Date.now();return}f=y.length-h;const b=Date.now()-l;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,h=y.length,l=Date.now()),this._onDashCallback("loading",{size:y.length,done:!1})},o,(y,b,k)=>this._params.onError(y,b,k))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=ai._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Na{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(u,d)=>{const c=u?parseFloat(u.replace(",",".")):NaN;return(isNaN(c)?0:c)*d},s=t.exec(e),n=s?.[1]==="-"?-1:1,o={years:i(s?.[2],n),months:i(s?.[3],n),weeks:i(s?.[4],n),days:i(s?.[5],n),hours:i(s?.[6],n),minutes:i(s?.[7],n),seconds:i(s?.[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=ct(i)),new fs(i,t,s=>{this.attachManifest(s,t,Ra(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(c,h)=>{const l=c.attributes.getNamedItem(h);return l?l.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const u=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),c=>{const h=c.getElementsByTagName("SegmentBase")[0],l=h&&o(h,"indexRange").split("-"),f=h&&h.getElementsByTagName("Initialization")[0],p=f&&o(f,"range").split("-");if(!p||!l){const m=c.parentElement;if(m?.getAttribute("contentType")==="text"){const E=c.getAttribute("id")??void 0,$=(i?i+"/":"")+c.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,R=m.getAttribute("lang")??void 0;$&&d.push({id:E,url:$,language:R})}return}const g=.1,y=Number(c.attributes.getNamedItem("bandwidth")?.value),b=(i?i+"/":"")+c.getElementsByTagName("BaseURL")[0].childNodes[0].data;let k;const w=c.attributes.getNamedItem("frameRate")?.value??void 0;k=w?mi(w):void 0,u.push({width:Number(c.attributes.getNamedItem("width")?.value),height:Number(c.attributes.getNamedItem("height")?.value),bandwidth:y,baseURL:b,failoverHosts:t,indexFrom:Number(l[0]),indexTo:Number(l[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:c.attributes.getNamedItem("codecs")?.value??void 0,mimeType:c.attributes.getNamedItem("mimeType")?.value??void 0,fps:k,bufferSize:g*y/8,bufferLength:g,name:c.attributes.getNamedItem("okQuality")?.value??void 0,id:c.attributes.getNamedItem("id")?.value??void 0})}),u.length)this._representations=u;else{this._onDashCallback("error");return}d.forEach(({id:c,language:h,url:l})=>{const f=document.createElement("track");l&&f.setAttribute("src",l),c&&f.setAttribute("id",c),h&&f.setAttribute("srclang",h),this._video.appendChild(f)}),this._representations.sort((c,h)=>h.bandwidth-c.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const u=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),c=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const h=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<h;f+=1){const p=c+(o.getUint32(n,!1)&2147483647),g=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/u,toTime:g/u,fromOffset:c,toOffset:p-1}),c=p,d=g}const l=e.refs[e.refs.length-1];l.toTime-l.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let s,n;const o=()=>{const c=this._findRef(this._video.currentTime);if(!c||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const h=this._appendVector[String(c.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let l;if(this._findRef(c.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}l=p.to-this._video.currentTime,l<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const g=this._buffer.getNextWithGap(p);g&&(this._video.currentTime=g.from)}catch(g){throw this._params.onError("GapSyncError",`Seek Error ${String(g)}`,g),g}},l*1e3)))}},u=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(c){throw this._params.onError("LoopError",`Dash Loop exception ${String(c)}`,c),c}u()},250)},d=()=>{if(!this._stream)try{const c=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ai({mediaSource:i,sourceBuffer:c,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(c){throw this._params.onError("DashSourceOpen",`Source open exception ${String(c)}`,c),c}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||u(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const c=this._video&&this._video.played.length;c&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(c-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),u=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||u<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,u)=>this._stream.append(o,u),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<i.to+n){const o=this._findRef(s.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(u,d)=>this._stream.remove(u,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(u,d)=>this._stream.remove(u,d)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||r.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let i;for(let s=0;s<t.length;s++){const n=t[s];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!i||n.fromTime<i.fromTime)&&(i=n)}if(!i){const s=t[t.length-1];if(e>s.toTime)return s}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>i&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var U;(function(a){a.STOPPED="stopped",a.MANIFEST_LOADED="manifest-loaded",a.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",a.METADATA_LOADED="metadata-loaded",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(U||(U={}));const _a=[U.PAUSED,U.PLAYING];class Ba{videoState=new q(U.STOPPED);subscription=new r.Subscription;video;buffer;dash;representations$=new r.ValueSubject([]);currentRepresentation$=new r.ValueSubject(void 0);params;textTracksManager=new Fe;droppedFramesManager=new Qt;elementSize$=new r.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Je(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ua(this.video),this.dash=new Na({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:s,category:r.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"DashProvider",category:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:u})},s=()=>{const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:u},n=Ke(this.video),o=(u,d)=>this.subscription.add(u.subscribe(d,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==V.Applying)&&(this.videoState.getState()===U.PLAYING||this.videoState.getState()===U.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(rt(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(r.map(u=>u.map(({track:d})=>d)))}),o(zt(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(U.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(u=>{this.buffer.fill(),e.currentBuffer$.next(u)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:u,message:d,thrown:c})=>({id:`DashLite_${u}`,category:r.ErrorCategory.WTF,message:d,thrown:c}))).subscribe(this.params.output.error$)).add(r.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{const u=this.currentRepresentation$.getValue(),d=this.representations$.getValue(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState()?.id,l=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),p=s();c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to);let g;if(!p&&r.isNonNullable(h))g=h;else{const y=Ee(this.video.buffered,this.video.currentTime*1e3),b=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,k=Math.min(y/b,1);g=Tt(d.map(({track:m})=>m),{container:f,throughput:l,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:k,playbackRate:this.video.playbackRate,current:d.find(({representation:m})=>m===u)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const w=t.autoVideoTrackLimits.getTransition();w&&e.autoVideoTrackLimits$.next(w.to)}return r.isNonNullable(g)?d.find(({track:y})=>y.id===g)?.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(u=>u.to===U.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(U.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((u,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?u.height<=d.height:u===d)).subscribe(u=>{const d=Ee(this.video.buffered,this.video.currentTime*1e3),c=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||c<=.5||!s())&&(this.dash.setQualityByRepresentation(u,!0),this.params.output.hostname$.next(Se(u.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(u=>{const{type:d,reused:c}=Li(u);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(c)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(u=>this.params.dependencies.throughputEstimator.addRawRtt(u))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return r.assertNever(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const n=s.name??s.id??s.height.toString(10),o=(s.name&&It(s.name))??r.videoSizeToQuality(s),u=s.bandwidth/1e3,d={width:s.width,height:s.height},c=s.fps;if(!o)continue;const h={id:n,quality:o,bitrate:u,size:d,fps:c};i.push({track:h,representation:s})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),t?.length>0){const s=[];for(const n of t){const o=n.id||`${n.language}_${Date.now()}`;s.push({id:o,type:"internal",url:n.url||"",language:n.language,isAuto:n.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(U.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return r.assertNonNullable(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(U.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:r.ErrorCategory.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=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!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(U.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&_a.includes(e)&&this.seek(n.position,n.forcePrecise),e){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_LOADED),this.prepare();return;case U.MANIFEST_LOADED:this.videoState.startTransitionTo(U.INITIAL_REPRESENTATION_SELECTED);return;case U.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(U.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case U.METADATA_LOADED:this.videoState.startTransitionTo(U.READY),this.dash.updateRefsForCurrentTime();return;case U.READY:i===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),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.video.pause()):s?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}}var he;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(he||(he={}));var ri;(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"})(ri||(ri={}));var Le;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Le||(Le={}));var H;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(H||(H={}));var Dt;(function(a){a.MP4="mp4",a.WEBM="webm"})(Dt||(Dt={}));var ni;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(ni||(ni={}));var Z;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Z||(Z={}));class Oi{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 s=0,n=i.length;s<n;s++)if(i[s].callback===t){i.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let s=0,n=i.length;s<n;s++){const o=i[s];try{o.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class ps extends Oi{constructor(){super(),this.listeners||Oi.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 ms=class{constructor(){Object.defineProperty(this,"signal",{value:new ps,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&&(ms.prototype[Symbol.toStringTag]="AbortController",ps.prototype[Symbol.toStringTag]="AbortSignal");function gs(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 Ma(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=a;if(!gs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(c,h){let l;h&&h.signal&&(l=h.signal,delete h.signal);const f=new t(c,h);return l&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,c)=>{const h=n&&n.prototype.isPrototypeOf(d)?d.signal:c?c.signal:void 0;if(h){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(h.aborted)return Promise.reject(l);const f=new Promise((p,g)=>{h.addEventListener("abort",()=>g(l),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([f,o(d,c)])}return o(d,c)},Request:n}}const gi=gs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),bs=gi?Ma({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,yt=gi?bs.fetch:window.fetch;gi?bs.Request:window.Request;const Re=gi?ms:window.AbortController;var Ct=(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 Va=(a,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-s-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},Fa=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",oi=Fa?Va:window.requestIdleCallback,Oa=16;let Ss=!1;try{Ss=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Oa}catch(a){console.error(a)}let Ua=class{bufferFull$=new r.Subject;error$=new r.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 s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Ss&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!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:r.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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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:r.assertNever(t)}}};var ui=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};let Ze=class{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}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}},ys=class extends Ze{},Ha=class extends Ze{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}},ja=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},Ya=class extends Ze{data;constructor(e){super(e),this.data=this.content}},Jt=class extends Ze{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},Ga=class extends Jt{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const u=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}},za=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},qa=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}};var bt;(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"})(bt||(bt={}));let Wa=class extends Jt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=bt.MONOSCOPIC;break;case 1:this.stereoMode=bt.TOP_BOTTOM;break;case 2:this.stereoMode=bt.LEFT_RIGHT;break;case 3:this.stereoMode=bt.STEREO_CUSTOM;break;case 4:this.stereoMode=bt.RIGHT_LEFT;break}this.cursor+=1}},Qa=class extends Jt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},Ja=class extends Jt{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},Xa=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},Ka=class extends Jt{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}},Za=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},er=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}};const tr={ftyp:Ha,moov:ja,mdat:Ya,sidx:Ga,trak:za,mdia:Xa,tkhd:Ka,minf:Za,sv3d:qa,st3d:Wa,prhd:Qa,proj:er,equi:Ja,unknown:ys};let ir=class{createBox(e,t){const i=tr[e];return i?new i(t):new ys(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return bi.createBox(i,new DataView(e.buffer,e.byteOffset))}};const bi=new ir;function Ht(a,e){const t=new TextDecoder("ascii");let i=a.byteOffset,s=[];for(;i<a.byteLength;){const n=t.decode(new DataView(a.buffer,i,1));if(n===e[s.length]?s.push(n):s=[],s.length===4&&s.join("")===e){const u=new DataView(a.buffer,i-7,4).getUint32(0);return i-7+u>a.byteLength?null:bi.createBox(e,new DataView(a.buffer,i-7))}i++}return null}function sr(a,e){const t=[];let i=0;for(;i<a.byteLength;){const s=Ht(new DataView(a.buffer,a.byteOffset+i,a.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function Nt(a){const e=[];let t=0;for(;t<a.byteLength;){const i=bi.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const ar=new TextDecoder("ascii"),rr=a=>ar.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",nr=a=>{const e=bi.createFromView(a);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,u={status:H.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,u})},or=a=>{const e=sr(a,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(a.buffer,a.byteOffset,t)}return null},ur=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ht(a,"sv3d")){e.is3dVideo=!0;const i=Ht(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=Ht(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=Ht(a,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},cr={validateData:rr,parseInit:ur,getIndexRange:()=>{},parseSegments:nr,parseFeedableSegmentChunk:or};var T;(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"})(T||(T={}));var P;(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"})(P||(P={}));const Ui={[T.EBML]:{type:P.Master},[T.EBMLVersion]:{type:P.UnsignedInteger},[T.EBMLReadVersion]:{type:P.UnsignedInteger},[T.EBMLMaxIDLength]:{type:P.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:P.UnsignedInteger},[T.DocType]:{type:P.String},[T.DocTypeVersion]:{type:P.UnsignedInteger},[T.DocTypeReadVersion]:{type:P.UnsignedInteger},[T.Void]:{type:P.Binary},[T.Segment]:{type:P.Master},[T.SeekHead]:{type:P.Master},[T.Seek]:{type:P.Master},[T.SeekID]:{type:P.Binary},[T.SeekPosition]:{type:P.UnsignedInteger},[T.Info]:{type:P.Master},[T.TimestampScale]:{type:P.UnsignedInteger},[T.Duration]:{type:P.Float},[T.Tracks]:{type:P.Master},[T.TrackEntry]:{type:P.Master},[T.Video]:{type:P.Master},[T.Projection]:{type:P.Master},[T.ProjectionType]:{type:P.UnsignedInteger},[T.ProjectionPrivate]:{type:P.Master},[T.Chapters]:{type:P.Master},[T.Cluster]:{type:P.Master},[T.Timestamp]:{type:P.UnsignedInteger},[T.SilentTracks]:{type:P.Master},[T.SilentTrackNumber]:{type:P.UnsignedInteger},[T.Position]:{type:P.UnsignedInteger},[T.PrevSize]:{type:P.UnsignedInteger},[T.SimpleBlock]:{type:P.Binary},[T.BlockGroup]:{type:P.Master},[T.EncryptedBlock]:{type:P.Binary},[T.Attachments]:{type:P.Master},[T.Tags]:{type:P.Master},[T.Cues]:{type:P.Master},[T.CuePoint]:{type:P.Master},[T.CueTime]:{type:P.UnsignedInteger},[T.CueTrackPositions]:{type:P.Master},[T.CueTrack]:{type:P.UnsignedInteger},[T.CueClusterPosition]:{type:P.UnsignedInteger},[T.CueRelativePosition]:{type:P.UnsignedInteger},[T.CueDuration]:{type:P.UnsignedInteger},[T.CueBlockNumber]:{type:P.UnsignedInteger},[T.CueCodecState]:{type:P.UnsignedInteger},[T.CueReference]:{type:P.Master},[T.CueRefTime]:{type:P.UnsignedInteger}},Ts=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=ci(a,t),s=i in Ui,n=s?Ui[i].type:P.Binary,o=a.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(a.buffer,a.byteOffset+t+1,u-1),c=o&255>>u,h=ci(d),l=c*2**((u-1)*8)+h,f=t+u;let p;return f+l>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,l),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+l,value:p,valueSize:l}},ci=(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},ze=(a,e)=>{switch(e){case P.SignedInteger:return a.getInt8(0);case P.UnsignedInteger:return ci(a);case P.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case P.String:return new TextDecoder("ascii").decode(a);case P.UTF8:return new TextDecoder("utf-8").decode(a);case P.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case P.Master:return a;case P.Binary:return a;default:r.assertNever(e)}},Lt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=Ts(i);if(!e(s))return;s.type===P.Master&&Lt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},dr=a=>{if(a.getUint32(0)!==T.EBML)return!1;let e,t,i;const s=Ts(a);return Lt(s.value,({tag:n,type:o,value:u})=>(n===T.EBMLReadVersion?e=ze(u,o):n===T.DocType?t=ze(u,o):n===T.DocTypeReadVersion&&(i=ze(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},vs=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],lr=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],hr=a=>{let e,t,i,s,n=!1,o=!1,u=!1,d,c,h=!1;const l=0;return Lt(a,({tag:f,type:p,value:g,valueSize:y})=>{if(f===T.SeekID){const b=ze(g,p);c=ci(b)}else f!==T.SeekPosition&&(c=void 0);return f===T.Segment?(e=g.byteOffset,t=g.byteOffset+y):f===T.Info?n=!0:f===T.SeekHead?o=!0:f===T.TimestampScale?i=ze(g,p):f===T.Duration?s=ze(g,p):f===T.SeekPosition&&c===T.Cues?d=ze(g,p):f===T.Tracks?Lt(g,({tag:b,type:k,value:w})=>b===T.ProjectionType?(h=ze(w,k)===1,!1):!0):n&&o&&vs.includes(f)&&(u=!0),!u}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(s,"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(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},fr=a=>{if(r.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},pr=(a,e)=>{let t=!1,i=!1;const s=u=>r.isNonNullable(u.time)&&r.isNonNullable(u.position),n=[];let o;return Lt(a,({tag:u,type:d,value:c})=>{switch(u){case T.Cues:t=!0;break;case T.CuePoint:o&&s(o)&&n.push(o),o={};break;case T.CueTime:o&&(o.time=ze(c,d));break;case T.CueTrackPositions:break;case T.CueClusterPosition:o&&(o.position=ze(c,d));break;default:t&&vs.includes(u)&&(i=!0)}return!(t&&i)}),o&&s(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:h}=u,l=n[d+1];return{status:H.NONE,time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},mr=a=>{let e=0,t=!1;try{Lt(a,i=>i.tag===T.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):lr.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},gr={validateData:dr,parseInit:hr,getIndexRange:fr,parseSegments:pr,parseFeedableSegmentChunk:mr},Es=1e4,br=3e4,Sr=5e3,yr=Es,Tr=({id:a,width:e,height:t,bitrate:i,fps:s,quality:n})=>{const o=(n?It(n):void 0)??r.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:s}},vr=({id:a,bitrate:e})=>({id:a,bitrate:e}),Er=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},kr=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),ti=a=>{const e=[];let t=0,i=a.length-1;for(;t<Es&&i>=0;)e.unshift(a[i]),t+=a[i].time.to-a[i].time.from,i--;return e};let Hi=class{onLastSegment$=new r.ValueSubject(!1);fullyBuffered$=new r.ValueSubject(!1);playingRepresentation$=new r.ValueSubject(void 0);playingRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;gaps=[];isSeekingLive=!1;subscription=new r.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Re;destroyAbortController=new Re;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,s,{fetcher:n,tuning:o,getCurrentPosition:u,compatibilityMode:d=!1,manifest:c}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.isLive=!!c?.dynamic,this.container=i,i){case Dt.MP4:this.containerParser=cr;break;case Dt.WEBM:this.containerParser=gr;break;default:r.assertNever(i)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=r.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);r.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 Ua(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),n=this.parsedInitData.get(t.id);r.assertNonNullable(i,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=r.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);r.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(r.isNullable(s)||r.isNullable(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),r.assertNonNullable(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const n=this.getCurrentPosition();r.isNonNullable(n)&&(this.searchGaps(i,t),this.maintain(n))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Re,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Ee(this.sourceBuffer.buffered,e),l=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){const c=Ee(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(u.includes(s))c="high";else{const h=u.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===H.FED&&!u.length&&Ee(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=i.at(-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const s of e)s.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from}),i=s.time.to;r.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.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=r.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const u of this.representations.keys()){const d=e.find(l=>l.id===u);d&&this.representations.set(u,d);const c=this.representations.get(u);if(!c)return;const h=ti(c.segmentReference.segments);this.segments.set(c.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);r.assertNonNullable(i);const s=ti(i.segmentReference.segments),n=this.initData.get(i.id);if(r.assertNonNullable(n,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),!(n instanceof ArrayBuffer))return;const o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t)return;const i=t.segmentReference.segments.map(u=>({...u,status:H.NONE,size:void 0})),s=this.segments.get(t.id)??[],n=s.at(-1)?.time.to??0,o=i?.findIndex(u=>Math.round(n)>=Math.round(u.time.from)&&Math.round(n)<=Math.round(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const u=ti(i);this.segments.set(t.id,[...u])}else{const u=i.slice(o+1);this.segments.set(t.id,[...s,...u])}}}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(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:l,time:{from:f,to:p}},g)=>{const y=f<=i&&p>=i,b=f>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&f<=i+k||p<=i+k;return(l===H.NONE||l===H.PARTIALLY_EJECTED&&b&&w&&this.sourceBuffer&&!Ct(this.sourceBuffer.buffered,i))&&b&&w});if(s===-1)return[];if(t!==Le.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<n.length&&(o<=c||u<=h);l++){const f=n[l];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,n,o=e;const{type:u}=t.segmentReference;switch(u){case Le.BYTE_RANGE:{s=t.segmentReference.url,n={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Le.TEMPLATE:{const c=e.at(0);s=new URL(c.url,t.segmentReference.baseUrl).toString(),o=[c];break}default:r.assertNever(u)}for(const c of o)c.status=H.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await r.abortable(d,async function*(){const c=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,c))}.bind(this))(),d.aborted))for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(c,h)=>{if(!d.aborted)try{this.onSomeDataLoaded(c,t.id,n?n.from:0,h,d)}catch(l){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:d,priority:i}).then(()=>this.failedDownloads=0,c=>{if(c.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(c)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(i)&&(t=Ee(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,s,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},u=l=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),l.segment.status=H.FED,"size"in l.segment&&(l.segment.size=l.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const p of this.segments.get(f.id)??[])p.status===H.FED&&p.time.from===l.segment.time.from&&p.time.to===l.segment.time.to&&(p.status=H.NONE);this.activeSegments.delete(l),this.detectGapsWhenIdle(t,[l.segment])},d=this.representations.get(t);if(!d)return;const c=d.segmentReference.type,h=e.byteLength;for(const l of this.activeSegments){const{segment:f}=l,p=c===Le.BYTE_RANGE,g=p?f.byte.to-f.byte.from+1:h;if(l.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const b=p?f.byte.from-i:0,k=p?f.byte.to-i:e.byteLength,w=b<s,m=k<=s;if(f.status===H.DOWNLOADING&&w&&m){f.status=H.DOWNLOADED,this.activeSegments.delete(l);const E=new DataView(e.buffer,e.byteOffset+b,g);this.sourceBufferTaskQueue.append(E,n).then($=>$&&!n.aborted?u(l):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&w&&(l.loadedBytes=Math.min(g,s-b),l.loadedBytes>l.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),$=l.loadedBytes===g?E:this.containerParser.parseFeedableSegmentChunk(E);$?.byteLength&&(f.status=H.PARTIALLY_FED,l.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,n).then(R=>{if(n.aborted)o();else if(R)l.fedBytes+=$.byteLength,l.fedBytes===g&&u(l);else{if(l.feedingBytes<g)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=oi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async u=>{if(!u)return;const{init:d,dataView:c,segments:h}=u,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,this.isLive?ti(h):h),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const h="size"in c?c.size??0:c.byte.to-c.byte.from;s+=h};for(const c of this.segments.values())for(const h of c){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===H.FED&&d(h)}if(u=isFinite(n)&&isFinite(o),!u){s=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const h of c){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===H.FED&&d(h)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const h=this.sourceBuffer.buffered.start(c)*1e3,l=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===H.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(l)){n=h,o=l;break}}if(u=isFinite(n)&&isFinite(o),!u&&i){s=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+c&&l.status===H.FED&&d(l)}return u=isFinite(n)&&isFinite(o),u?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 s={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,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){s=void 0;break}u>i.time.from&&u<i.time.to&&(s.from=u),o<i.time.to&&o>i.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=oi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:n})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:n}=s;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),u=Math.ceil(s.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=u),c=e.filter(h=>o>=h.from-t&&o<=h.to+t||u>=h.from-t&&u<=h.to+t);d||(c.length===1?s.status=H.PARTIALLY_EJECTED:s.status=H.NONE)}}};var wt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(wt||(wt={}));let $r=class{throughputEstimator;requestQuic;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);abortAllController=new Re;subscription=new r.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}=Li(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=r.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ct(t));const i=yield yt(t,{signal:this.abortAllController.signal}).catch(Vt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=r.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?wt.HEADER:wt.PARAM,range:i,onProgress:s,priority:n="auto",signal:o,measureThroughput:u=!0}={}){let d=e;const c=new Headers;if(i)switch(t){case wt.HEADER:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case wt.PARAM:{const S=new URL(d,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),d=S.toString();break}default:r.assertNever(t)}this.requestQuic&&(d=ct(d));let h=this.abortAllController.signal,l;if(o){const S=new Re;if(l=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(o,"abort")).subscribe(()=>{try{S.abort()}catch(L){Vt(L)}}),this.abortAllController.signal.aborted||o.aborted)try{S.abort()}catch(L){Vt(L)}h=S.signal}const f=r.now(),p=yield yt(d,{priority:n,headers:c,signal:h}).catch(Vt),g=r.now();if(this.throughputEstimator?.addRawRtt(g-f),!p)return l?.unsubscribe(),null;if(!p.ok||!p.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const y=parseInt(p.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!y){const S=yield p.arrayBuffer();return this.throughputEstimator?.addRawSpeed(S.byteLength,r.now()-g),s?.(new DataView(S),S.byteLength),l?.unsubscribe(),S}if(!s&&!u)return l?.unsubscribe(),p.arrayBuffer();const[b,k]=p.body.tee(),w=b.getReader();u&&this.throughputEstimator?.trackStream(k);let m=0;const E=new ArrayBuffer(y),$=new Uint8Array(E),R=new DataView(E);let _=!1;const C=S=>{l?.unsubscribe(),_=!0,Vt(S)},I=r.abortable(h,async function*({done:S,value:L}){if(m===0&&this.lastRequestFirstBytes$.next(r.now()-f),h.aborted){l?.unsubscribe();return}!S&&L&&($.set(L,m),m+=L.byteLength,s?.(R,m),yield w?.read().then(I,C))}.bind(this));return yield w?.read().then(I,C),l?.unsubscribe(),_?null:E}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Le.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Le.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:r.assertNever(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Le.BYTE_RANGE)return null;const{from:s,to:n}=e.initRange;let o=s,u=n,d=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,s),u=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:u},priority:i,measureThroughput:!1});if(!l)return null;const f=new DataView(l,s-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),g=e.indexRange??t.getIndexRange(p);if(!g)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,g.from-o,g.to-g.from+1);else{const k=yield this.fetch(e.url,{range:g,priority:i,measureThroughput:!1});if(!k)return null;y=new DataView(k)}const b=t.parseSegments(y,p,g);return{init:p,dataView:new DataView(l),segments:b}}.bind(this));fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==Le.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(o=>({...o,status:H.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))};const Vt=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},ji=a=>{if(!a.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},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),s=i?.[1]==="-"?-1:1,n={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},yi=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(i)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>r.isNullable(n)?u:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Ar=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],u=o.children,d=n.getAttribute("type")==="dynamic",c=n.getAttribute("availabilityStartTime"),h=c?new Date(c).getTime():void 0;let l;const f=n.getAttribute("mediaPresentationDuration"),p=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)l=ji(f);else if(p){const m=ji(p);r.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let b=0;const k=n.getAttribute("profiles")?.split(",")??[],w=k.includes(ri.WEBM_AS_IN_FFMPEG)||k.includes(ri.WEBM_AS_IN_SPEC)?Dt.WEBM:Dt.MP4;for(const m of u){const E=m.getAttribute("mimeType"),$=m.getAttribute("codecs"),R=m.getAttribute("contentType")??E?.split("/")[0],_=m.getAttribute("profiles")?.split(",")??[],C=m.querySelectorAll("Representation"),I=m.querySelector("SegmentTemplate");if(R===he.TEXT){for(const S of C){const L=S.getAttribute("id")||"",N=m.getAttribute("lang"),j=S.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(j,e).toString(),ne=L.includes("_auto");s[he.TEXT].push({id:L,lang:N,isAuto:ne,kind:he.TEXT,url:ie})}continue}for(const S of C){const L=S.getAttribute("mimeType")??E,N=S.getAttribute("codecs")??$??"",j=S.getAttribute("contentType")??L?.split("/")[0]??R,ie=m.getAttribute("profiles")?.split(",")??[],ne=parseInt(S.getAttribute("width")??"",10),x=parseInt(S.getAttribute("height")??"",10),G=parseInt(S.getAttribute("bandwidth")??"",10)/1e3,K=S.getAttribute("frameRate")??"",oe=S.getAttribute("quality")??void 0,pe=K?mi(K):void 0,Oe=S.getAttribute("id")??(b++).toString(10),_t=j==="video"?`${x}p`:j==="audio"?`${G}Kbps`:N,vt=`${Oe}@${_t}`,z=S.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(z,e).toString(),ye=[...k,..._,...ie];let de;const et=S.querySelector("SegmentBase"),se=S.querySelector("SegmentTemplate")??I;if(et){const ue=S.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[le,Ue]=ue.split("-").map($e=>parseInt($e,10)),Te={from:le,to:Ue},Ne=S.querySelector("SegmentBase")?.getAttribute("indexRange"),[ht,tt]=Ne?Ne.split("-").map($e=>parseInt($e,10)):[],_e=Ne?{from:ht,to:tt}:void 0;de={type:Le.BYTE_RANGE,url:ce,initRange:Te,indexRange:_e}}else if(se){const ue={representationId:S.getAttribute("id")??void 0,bandwidth:S.getAttribute("bandwidth")??void 0},le=parseInt(se.getAttribute("timescale")??"",10),Ue=se.getAttribute("initialization")??"",Te=se.getAttribute("media"),Ne=parseInt(se.getAttribute("startNumber")??"",10)??1,ht=yi(Ue,ue);if(!Te)throw new ReferenceError("No media attribute in SegmentTemplate");const tt=se.querySelectorAll("SegmentTimeline S")??[],_e=[];let $e=0;if(tt.length){let ft=Ne,Ae=0;for(const pt of tt){const we=parseInt(pt.getAttribute("d")??"",10),ae=parseInt(pt.getAttribute("r")??"",10)||0,Be=parseInt(pt.getAttribute("t")??"",10);Ae=Number.isFinite(Be)?Be:Ae;const ve=we/le*1e3,He=Ae/le*1e3;for(let it=0;it<ae+1;it++){const Bt=yi(Te,{...ue,segmentNumber:ft.toString(10),segmentTime:(Ae+it*we).toString(10)}),Xt=(He||0)+it*ve,Et=Xt+ve;ft++,_e.push({time:{from:Xt,to:Et},url:Bt})}Ae+=(ae+1)*we,$e+=(ae+1)*ve}}else if(r.isNonNullable(l)){const Ae=parseInt(se.getAttribute("duration")??"",10)/le*1e3,pt=Math.ceil(l/Ae);let we=0;for(let ae=1;ae<pt;ae++){const Be=yi(Te,{...ue,segmentNumber:ae.toString(10),segmentTime:we.toString(10)});_e.push({time:{from:we,to:we+Ae},url:Be}),we+=Ae}}de={type:Le.TEMPLATE,baseUrl:ce,initUrl:ht,totalSegmentsDurationMs:$e,segments:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!L)continue;const ke={video:he.VIDEO,audio:he.AUDIO,text:he.TEXT}[j];ke&&s[ke].push({id:vt,kind:ke,segmentReference:de,profiles:ye,duration:l,bitrate:G,mime:L,codecs:N,width:ne,height:x,fps:pe,quality:oe})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:w,representations:s}},ki=1e3,Yi=["timeupdate","progress","play","seeked","stalled","waiting"];var De;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(De||(De={}));let wr=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new r.Subscription;representationSubscription=new r.Subscription;fetcher;state$=new q(De.NONE);currentVideoRepresentation$=new r.ValueSubject(void 0);currentVideoRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);isLive$=new r.ValueSubject(!1);liveDuration$=new r.ValueSubject(0);liveAvailabilityStartTime$=new r.ValueSubject(void 0);bufferLength$=new r.ValueSubject(0);liveLoadBufferLength$=new r.ValueSubject(0);forceEnded$=new r.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Re;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new $r({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=r.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=be(t,i,X.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(De.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(De.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=r.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=Ar(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||s===he.TEXT);return this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,n])=>[s,n.filter(i)]))}}.bind(this));async seekLive(e){r.assertNonNullable(this.element),this.manifestUrlString=be(this.manifestUrlString,e,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=r.abortable(this.destroyController.signal,async function*(e,t){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(De.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Hi(he.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(t)&&(this.audioBufferManager=new Hi(he.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(r.interval(ki).subscribe(o=>{if(this.element?.paused){const u=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=be(this.manifestUrlString,u+1e3,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Yi.map(o=>r.fromEvent(this.element,o))).pipe(r.throttle(ki),r.map(o=>this.element?Ee(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(u=>{let d=0;if(u){const c=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-c}this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async u=>{r.assertNonNullable(this.element);const d=this.element.playbackRate,c=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P),h=br*d,l=yr*d,f=Sr*d;o=u>o?u:o;const p=c===0&&u<f,g=c!==0&&u<h+f&&u>=h,y=c!==0&&u<h;if(y||g){const b=o-(h+l),k=Math.trunc(c+b/d);let w;u?k>0?w=k:w=0:w=c,this.manifestUrlString=be(this.manifestUrlString,w,X.DASH_CMAF_OFFSET_P)}(p||y||g)&&(await this.updateLive(),o=0)}))}const s=r.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=r.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:s,someBufferEnded:n}).pipe(r.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(o=>!o.updating))try{this.source?.endOfStream()}catch(o){this.error$.next({id:"EndOfStream",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(r.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(De.REPRESENTATIOS_READY)}.bind(this));initBuffer(){r.assertNonNullable(this.element),this.state$.setState(De.RUNNING),this.subscription.add(r.merge(...Yi.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[he.VIDEO]:this.videoBufferManager,[he.AUDIO]:this.audioBufferManager,[he.TEXT]:null}[e]?.switchTo(t)}seek(e,t){r.assertNonNullable(this.element),r.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),Ct(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(De.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};class Pr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Dr{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 s=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:s,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 s=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>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 Cr=`#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;}`,Lr=`#ifdef GL_ES
37
+ `}),S}return c?.recordSwitch(C),C};var ye=a=>new URL(a).hostname;const fa=300,zt=(a,e=fa)=>new r.Observable(t=>{const{width:i,height:s}=a.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(r.debounceFn(o=>{const u=o[0];if(!u)return;let d,c;u.contentBoxSize&&u.contentBoxSize[0]?(c=u.contentBoxSize[0].blockSize,d=u.contentBoxSize[0].inlineSize):u.contentRect&&(d=u.contentRect.width,c=u.contentRect.height),r.isNonNullable(d)&&r.isNonNullable(c)&&t.next({width:d,height:c})},e));return n.observe(a),()=>n.disconnect()});class Qt{onDroopedVideoFramesLimit$=new r.Subject;subscription=new r.Subscription;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new r.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(r.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=r.interval(this.droppedFramesChecker.checkTime).pipe(r.filter(()=>this.playing),r.filter(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(r.debounce(this.droppedFramesChecker.checkTime)),i=r.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&&!r.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,s=t-this.prevDroppedVideoFrames,n=1-(i-s)/i;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&r.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],[s])=>r.isLower(i,s)?-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 Mt={};var O;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(O||(O={}));const re=(a,e)=>new r.Observable(t=>{const i=s=>t.next(s);return a.on(e,i),()=>a.off(e,i)});class Mi{subscription=new r.Subscription;videoState=new q(O.DOWNLOADING_LIB);video;player;params;textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);frameRatesByFrameHeight={};isLive$=new r.ValueSubject(void 0);maxSeekBackTime$=new r.ValueSubject(1/0);availableFrom$=new r.ValueSubject(void 0);elementSize$=new r.ValueSubject(void 0);liveOffset=new Wt;constructor(e){this.video=Je(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${s?.toString?.()}`,thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Mt.MediaPlayer=s.MediaPlayer,Mt.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Mt.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Mt.Debug,"dashjs not loaded"),this.player=Mt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?mi(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&ea(this.player),Xs(this.player),this.params.tuning.requestQuick&&Zs(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(O.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,T)=>this.subscription.add(m.subscribe(T,i));s(zt(this.video),this.elementSize$),s(re(this.player,"error").pipe(r.map(m=>{const T=typeof m.error=="object"?m.error.code:m.error,$=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${T}`,message:$}})),e.error$),s(re(this.player,"playbackError").pipe(r.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({newQuality:m})=>this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===m)?.track));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:m})=>m===O.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(Ve(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===m)?.track},m=>{if(r.isNullable(m))return;const T=this.videoTracks$.getValue().find(({track:$})=>$.id===m.id)?.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:n,onError:i}))},i)),this.subscription.add(Ve(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),s(re(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:T}})=>{const $=this.player.getDashMetrics(),R=$.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),_=$.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??exports.HttpConnectionType.HTTP1,C={1:!0,0:!1}[R]??void 0;this.params.output.httpConnectionType$.next(_),this.params.output.httpConnectionReused$.next(C),e.hostname$.next(ye(T))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:T,availableFrom:$}}})=>{this.isLive$.next(T),this.availableFrom$.next($.getTime()),T||e.duration$.next(m);const R=[],_=this.player.getQualityFor("video");let C;for(const I of this.player.getBitrateInfoListFor("video")){const S=I.qualityIndex.toString(10),L=r.videoSizeToQuality(I),N=I.bitrate/1e3,j={width:I.width,height:I.height},ie=this.frameRatesByFrameHeight[I.height];if(L){const ne={id:S,quality:L,bitrate:N,size:j,fps:ie};R.push({track:ne,bitrateInfo:I}),I.qualityIndex===_&&(C=ne)}}this.videoTracks$.next(R),e.availableVideoTracks$.next(R.map(({track:I})=>I)),C&&e.currentVideoTrack$.next(C),this.videoState.setState(O.STREAM_INITIALIZED),this.videoState.startTransitionTo(O.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const T=m.requestEndDate.getTime()-m.firstByteDate.getTime(),$=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,T)}),s(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=Tt(this.videoTracks$.getValue().map(({track:_})=>_),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),$=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to);const R=this.videoTracks$.getValue().find(({track:_})=>_===T);R?.bitrateInfo&&this.player.setQualityFor("video",R?.bitrateInfo.qualityIndex,!1)}),s(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:m})=>m),r.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(r.map(({time:m})=>m??0));s(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:T})=>this.params.output.liveTime$.next(m+T*1e3)),s(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(r.map(()=>ds(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(O.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(O.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(O.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===O.READY&&this.videoState.setState(O.READY)}),s(this.isLive$,e.isLive$),s(zt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const u=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));s(u,this.syncPlayback);const{playbackDuration$:d,ping$:c,connectionType$:h,connectionReused$:l}=Ks(this.player);s(h,this.params.output.httpConnectionType$),s(l,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(c.pipe(r.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(m=>m<60))}),({isLive:m,isShort:T})=>{const $=!m&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),s(o.pipe(r.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(re(this.player,"manifestLoaded"),m=>{if(m.data?.Period?.AdaptationSet){const T=[];for(const $ of m.data?.Period?.AdaptationSet)if($.contentType==="text"){const R=$.Representation?.id,_=new URL($.Representation?.BaseURL,m.data?.baseUri).toString(),C="internal",I=$.lang;T.push({id:R,url:_,type:C,language:I})}t.internalTextTracks.startTransitionTo(T)}}),this.subscription.add(dt(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:g,inPiP$:y,inFullscreen$:b,pause$:k,playing$:A}=Ke(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:A,pause$:k,tracks$:this.videoTracks$.pipe(r.map(m=>m.map(({track:T})=>T)))}),this.subscription.add(Qe(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(rt(this.video,t.playbackRate,g,i)),this.subscription.add(y.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(O.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(O.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=Se(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,X.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(O.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(O.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===O.DOWNLOADING_LIB||e===O.STREAM_INITIALIZED))switch(i?.to!==exports.PlaybackState.PAUSED&&s.state===V.Requested&&e!==O.STOPPED&&t!==exports.PlaybackState.STOPPED&&(n?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case exports.PlaybackState.STOPPED:{switch(e){case O.STOPPED:break;case O.PLAYING:case O.PAUSED:case O.READY:this.stop();break;default:r.assertNever(e)}break}case exports.PlaybackState.READY:{switch(e){case O.STOPPED:this.prepare();break;case O.PLAYING:case O.PAUSED:case O.READY:break;default:r.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case O.PLAYING:break;case O.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case O.READY:this.play();break;case O.STOPPED:this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case O.PLAYING:this.pause(),this.liveOffset.pause();break;case O.PAUSED:break;case O.READY:this.videoState.setState(O.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case O.STOPPED:this.prepare();break;default:r.assertNever(e)}break}default:r.assertNever(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}Xe(this.video),this.params.output.element$.next(void 0)}}var It=a=>{switch(a){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}};const Vi=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 nt=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!Vi(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return Vi(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function be(){return r.now()}function hs(a){return be()-a}function Fi(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=o=>i.test(o);return{resolve:(o,u,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let c=o.indexOf("?")>-1?"&":"?";return d&&(o+=c+"lowLat=1",c="&"),u&&(o+=c+"_rnd="+Math.floor(999999999*Math.random())),o}}}function pa(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function ii(a,e,t,i){const s=window.XMLHttpRequest;let n,o,u,d=!1,c=0,h,l,f=!1,p="arraybuffer",g=7e3,y=2e3,b=()=>{if(d)return;r.assertNonNullable(h);const N=hs(h);let j;if(N<y){j=y-N,setTimeout(b,j);return}y*=2,y>g&&(y=g),o&&o.abort(),o=new s,R()};const k=N=>(n=N,L),A=N=>(l=N,L),m=()=>(p="json",L),T=()=>{if(!d){if(--c>=0){b(),i&&i();return}d=!0,l&&l(),t&&t()}},$=N=>(f=N,L),R=()=>{h=be(),o=new s,o.open("get",a);let N=0,j,ie=0;const ne=()=>(r.assertNonNullable(h),Math.max(h,Math.max(j||0,ie||0)));if(n&&o.addEventListener("progress",x=>{const G=be();n.updateChunk&&x.loaded>N&&(n.updateChunk(ne(),x.loaded-N),N=x.loaded,j=G)}),u&&(o.timeout=u,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const x=o.status;if(x>=200&&x<300){if(o.response.byteLength&&n){const G=o.response.byteLength-N;G&&n.updateChunk&&n.updateChunk(ne(),G)}l&&l(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const x=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ie=be(),o.removeEventListener("readystatechange",x))};o.addEventListener("readystatechange",x)}return o.responseType=p,o.send(),L},L={withBitrateReporting:k,withParallel:$,withJSONResponse:m,withRetryCount:N=>(c=N,L),withRetryInterval:(N,j)=>(r.isNonNullable(N)&&(y=N),r.isNonNullable(j)&&(g=j),L),withTimeout:N=>(u=N,L),withFinally:A,send:R,abort:()=>{o&&(o.abort(),o=void 0),d=!0,l&&l()}};return L}const ma=100,ga=2e3,ba=500;let Sa=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-ba;if(t-e>ga){let i=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,u=n.end-n.start;i+=o;const d=n.bytes*o/u;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&i>0){const n=s*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(s)}/${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>ma&&(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 ya{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,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=be(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ii(t,n,()=>s("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=be()}_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=be();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,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=s,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 u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=i,n._retryCB=s,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 Zt=1e4,ei=3,Ta=300,va=2e3,Ea=6e4,ka=10,$a=1,wa=500;class Aa{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 Sa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Fi(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=Fi(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 s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u)n=this.manifest[u],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!i||i.bitrate>n.bitrate)&&(i=n));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{pa(s,"progress",()=>{s.buffered.length?(s.currentTime=s.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 ya(ei,Zt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let n=!1,o=null,u=null,d=null,c=null,h=!1;const l=()=>{const T=n&&(!h||h===this.rep);return T||t("Not running!"),T},f=(T,$,R)=>{d&&d.abort(),d=ii(this.urlResolver.resolve(T,!1),$,R,()=>this._retryCallback()).withTimeout(Zt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ei).withFinally(()=>{d=null}).send()},p=(T,$,R)=>{r.assertNonNullable(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),$,R,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},g=T=>{const $=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${$}=>${T}`),i.playbackRate=T)},y=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)g(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){g(1);return}const R=be()-1e4;let _=0;for(let I=0;I<this.bufferStates.length;I++){const S=this.bufferStates[I];T=Math.min(T,S.buf),S.ts<R&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${T} drop=${_} jitter=${this.sourceJitter}`);let C=T-$a;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?g(1.15):C>1?g(1.1):C>.3?g(1.05):g(1)}},k=T=>{let $;const R=()=>$&&$.start?$.start.length:0,_=x=>$.start[x]/1e3,C=x=>$.dur[x]/1e3,I=x=>$.fragIndex+x,S=(x,G)=>({chunkIdx:I(x),startTS:_(x),dur:C(x),discontinuity:G}),L=()=>{let x=0;if($&&$.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,oe=G;this.sourceJitter>1&&(oe+=this.sourceJitter-1);let me=$.dur.length-1;for(;me>=0&&(oe-=$.dur[me],!(oe<=0));--me);x=Math.min(me,$.dur.length-1-K),x=Math.max(x,0)}return S(x,!0)},N=x=>{const G=R();if(!(G<=0)){if(r.isNonNullable(x)){for(let K=0;K<G;K++)if(_(K)>x)return S(K)}return L()}},j=x=>{const G=R(),K=x?x.chunkIdx+1:0,oe=K-$.fragIndex;if(!(G<=0)){if(!x||oe<0||oe-G>ka)return t(`Resync: offset=${oe} bChunks=${G} chunk=`+JSON.stringify(x)),L();if(!(oe>=G))return S(K-$.fragIndex,!1)}},ie=(x,G,K)=>{c&&c.abort(),c=ii(this.urlResolver.resolve(x,!0,this.lowLatency),G,K,()=>this._retryCallback()).withTimeout(Zt).withRetryCount(ei).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,G)=>{ie(T,K=>{if(!l())return;$=K;const oe=!!$.lowLatency;oe!==this.lowLatency&&y(oe);let me=0;for(let Oe=0;Oe<$.dur.length;++Oe)me+=$.dur[Oe];me>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/$.dur.length)),s({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,x(N(G))},()=>this._handleNetworkError())},nextChunk:j}},A=()=>{n=!1,u&&u.abort(),d&&d.abort(),c&&c.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:T=>{const{videoElement:$,logger:R}=this.params;let _=k(e.jidxUrl),C,I,S,L,N=0,j,ie,ne;const x=()=>{j&&(clearTimeout(j),j=void 0);const z=Math.max(wa,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=N+z,Te=be(),de=Math.min(1e4,ce-Te);N=Te;const et=()=>{c||l()&&_.seek(()=>{l()&&(N=be(),G(),x())})};de>0?j=window.setTimeout(()=>{this.paused?x():et()},de):et()},G=()=>{let z;for(;z=_.nextChunk(L);)L=z,_t(z);const ce=_.nextChunk(S);if(ce){if(S&&ce.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(A(),this._initPlayerWith(e));return}Oe(ce)}else x()},K=(z,ce)=>{if(!l()||!this.sourceBuffer)return;let Te,de,et;const se=$e=>{window.setTimeout(()=>{l()&&K(z,ce)},$e)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),se(100);else{const $e=be(),ue=$.currentTime;!this.paused&&$.buffered.length>1&&ie===ue&&$e-ne>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ie!==ue&&(ie=ue,ne=$e);const le=this._getBufferSizeSec();if(le>30)R(`Buffered ${le} seconds; delaying appendBuffer`),se(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:$e,buf:le}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(Ue){if(Ue.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),et=this.sourceBuffer.buffered.length,et!==0&&(Te=this.sourceBuffer.buffered.start(0),de=ue,de-Te>4&&this.sourceBuffer.remove(Te,de-3)),se(1e3);else throw Ue}}},oe=()=>{I&&C&&(R([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(S)]),K(I,function(){I=null,G()}))},me=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Oe=z=>{l()&&p(me(z),(ce,Te)=>{if(l()){if(Te/=1e3,I=ce,S=z,o=z.startTS,Te){const de=Math.min(10,z.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*de:de}oe()}},()=>this._handleNetworkError())},_t=z=>{l()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(z),!1)))},vt=z=>{l()&&(e.cachedHeader=z,K(z,()=>{C=!0,oe()}))};n=!0,_.seek(z=>{if(l()){if(N=be(),!z){x();return}L=z,!r.isNullable(T)||z.startTS>T?Oe(z):(S=z,G())}},T),e.cachedHeader?vt(e.cachedHeader):f(e.headerUrl,vt,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>o},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),r.isNonNullable(s)&&(s+=.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,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let f,p,g;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(p=this._getBufferSizeSec(),g=l/this.bitrate,p>10&&g>.8||p>15&&g>.5||p>20&&g>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}f=this._selectQuality(l),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${l}`)},n=(()=>({updateChunk:(f,p)=>{const g=be();if(this.chunkRateEstimator.addInterval(f,g,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:g-f,speed:b}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,u,d=!0;const c=()=>{let l=n.get();if(l&&u&&this.autoQuality){if(d&&l>u&&hs(o)<3e4)return;i(l)}d=this.autoQuality};return{updateChunk:(l,f)=>{const p=n.updateChunk(l,f);return p&&c(),p},notifySwitch:l=>{const f=be();l<u&&(o=f),u=l}}}_fetchManifest(e,t,i){this.manifestRequest=ii(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Zt).withRetryCount(ei).withRetryInterval(Ta,va).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;nt(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,n=o=>{const u=[];return o?.length?(o.forEach((d,c)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=c,u.push(d))}),u.sort(function(d,c){return d.video&&c.video?c.video.height-d.video.height:c.bitrate-d.bitrate}),u):(i({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Ea))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var F;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(F||(F={}));const Pa=[F.PAUSED,F.PLAYING,F.READY],Da=[F.PAUSED,F.PLAYING,F.READY];class Ca{subscription=new r.Subscription;video;videoState=new q(F.STOPPED);dash;representations$=new r.ValueSubject([]);textTracksManager=new Fe;droppedFramesManager=new Qt;maxSeekBackTime$=new r.ValueSubject(1/0);zeroTime$=new r.ValueSubject(void 0);liveOffset=new Wt;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Je(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(ye(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=Ke(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(r.map(s=>s.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===F.READY&&this.videoState.setState(F.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(F.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(Qe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(rt(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:s}})=>{const n=s&&r.videoQualityToHeight(s);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case F.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case F.MANIFEST_READY:case F.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case F.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case F.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(s.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}createLiveDashPlayer(){const e=new Aa({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&r.isNonNullable(t)?t:Tt(e.map(({track:c})=>c),{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=s?.id,o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(o||n!==u)&&this.setVideoTrack(s),d&&this.setAutoQuality(i),o||d||n!==u){const c=e.find(({track:h})=>h.id===n)?.representation;r.assertNonNullable(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;r.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(),s=t===exports.PlaybackState.PAUSED&&i===F.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const n=s.name??s.index.toString(10),o=It(s.name)??r.videoSizeToQuality(s.video),u=s.bitrate/1e3,d={...s.video};if(!o)continue;const c={id:n,quality:o,bitrate:u,size:d};i.push({track:c,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===F.MANIFEST_READY&&this.videoState.setState(F.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),r.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(),s=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!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(F.STOPPED));return}if(t)return;const o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Da.includes(e)&&(o||u)){this.prepare();return}if(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&Pa.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_READY),this.dash.attachSource(Se(this.params.source.url));return;case F.MANIFEST_READY:this.videoState.startTransitionTo(F.READY),this.prepare();break;case F.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(F.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(F.PLAYING);const d=s?.from;d&&d===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(F.PAUSED)})}return;case F.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(F.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case F.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(F.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(F.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(Se(this.params.source.url,d))}return;default:return r.assertNever(e)}}}var Li=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?exports.HttpConnectionType.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},ke=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,n=a.end(i)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const La=a=>{const e=document.createElement("a");return e.href=a,e.origin},xa=a=>{const e=document.createElement("a");return e.href=a,e.host};class fs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,n,o){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(this._xhr){if(this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(i=>i.split(":").map(s=>s.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(xa(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",t,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class ai{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,u=s.length;o<u;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,n,o,u){this.abort(()=>{let d=0;const c=Date.now();let h=0,l=0,f=0;const p=y=>{s(ai._str2ua(y.substr(d))),d=y.length};let g=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(g=ct(g)),this._lastXhr=new fs(g,e.failoverHosts,y=>{this._lastXhr=void 0,p(y);const b=Date.now()-c;this._params.onBandwidthChange({size:y.length,duration:b,speed:8*y.length/(b/1e3)}),this._onDashCallback("loading",{size:y.length,done:!0}),n?.()},y=>{if(y.length-d>u&&p(y),l===0){l=Date.now();return}f=y.length-h;const b=Date.now()-l;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,h=y.length,l=Date.now()),this._onDashCallback("loading",{size:y.length,done:!1})},o,(y,b,k)=>this._params.onError(y,b,k))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=ai._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Ra{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(u,d)=>{const c=u?parseFloat(u.replace(",",".")):NaN;return(isNaN(c)?0:c)*d},s=t.exec(e),n=s?.[1]==="-"?-1:1,o={years:i(s?.[2],n),months:i(s?.[3],n),weeks:i(s?.[4],n),days:i(s?.[5],n),hours:i(s?.[6],n),minutes:i(s?.[7],n),seconds:i(s?.[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=ct(i)),new fs(i,t,s=>{this.attachManifest(s,t,La(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(c,h)=>{const l=c.attributes.getNamedItem(h);return l?l.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const u=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),c=>{const h=c.getElementsByTagName("SegmentBase")[0],l=h&&o(h,"indexRange").split("-"),f=h&&h.getElementsByTagName("Initialization")[0],p=f&&o(f,"range").split("-");if(!p||!l){const m=c.parentElement;if(m?.getAttribute("contentType")==="text"){const T=c.getAttribute("id")??void 0,$=(i?i+"/":"")+c.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,R=m.getAttribute("lang")??void 0;$&&d.push({id:T,url:$,language:R})}return}const g=.1,y=Number(c.attributes.getNamedItem("bandwidth")?.value),b=(i?i+"/":"")+c.getElementsByTagName("BaseURL")[0].childNodes[0].data;let k;const A=c.attributes.getNamedItem("frameRate")?.value??void 0;k=A?mi(A):void 0,u.push({width:Number(c.attributes.getNamedItem("width")?.value),height:Number(c.attributes.getNamedItem("height")?.value),bandwidth:y,baseURL:b,failoverHosts:t,indexFrom:Number(l[0]),indexTo:Number(l[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:c.attributes.getNamedItem("codecs")?.value??void 0,mimeType:c.attributes.getNamedItem("mimeType")?.value??void 0,fps:k,bufferSize:g*y/8,bufferLength:g,name:c.attributes.getNamedItem("okQuality")?.value??void 0,id:c.attributes.getNamedItem("id")?.value??void 0})}),u.length)this._representations=u;else{this._onDashCallback("error");return}d.forEach(({id:c,language:h,url:l})=>{const f=document.createElement("track");l&&f.setAttribute("src",l),c&&f.setAttribute("id",c),h&&f.setAttribute("srclang",h),this._video.appendChild(f)}),this._representations.sort((c,h)=>h.bandwidth-c.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const u=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),c=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const h=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<h;f+=1){const p=c+(o.getUint32(n,!1)&2147483647),g=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/u,toTime:g/u,fromOffset:c,toOffset:p-1}),c=p,d=g}const l=e.refs[e.refs.length-1];l.toTime-l.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let s,n;const o=()=>{const c=this._findRef(this._video.currentTime);if(!c||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const h=this._appendVector[String(c.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let l;if(this._findRef(c.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}l=p.to-this._video.currentTime,l<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const g=this._buffer.getNextWithGap(p);g&&(this._video.currentTime=g.from)}catch(g){throw this._params.onError("GapSyncError",`Seek Error ${String(g)}`,g),g}},l*1e3)))}},u=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(c){throw this._params.onError("LoopError",`Dash Loop exception ${String(c)}`,c),c}u()},250)},d=()=>{if(!this._stream)try{const c=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ai({mediaSource:i,sourceBuffer:c,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(c){throw this._params.onError("DashSourceOpen",`Source open exception ${String(c)}`,c),c}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||u(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const c=this._video&&this._video.played.length;c&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(c-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),u=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||u<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,u)=>this._stream.append(o,u),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<i.to+n){const o=this._findRef(s.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(u,d)=>this._stream.remove(u,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(u,d)=>this._stream.remove(u,d)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||r.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let i;for(let s=0;s<t.length;s++){const n=t[s];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!i||n.fromTime<i.fromTime)&&(i=n)}if(!i){const s=t[t.length-1];if(e>s.toTime)return s}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>i&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var U;(function(a){a.STOPPED="stopped",a.MANIFEST_LOADED="manifest-loaded",a.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",a.METADATA_LOADED="metadata-loaded",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(U||(U={}));const Ia=[U.PAUSED,U.PLAYING];class Na{videoState=new q(U.STOPPED);subscription=new r.Subscription;video;buffer;dash;representations$=new r.ValueSubject([]);currentRepresentation$=new r.ValueSubject(void 0);params;textTracksManager=new Fe;droppedFramesManager=new Qt;elementSize$=new r.ValueSubject(void 0);dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Je(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new na(this.video),this.dash=new Ra({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:s,category:r.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"DashProvider",category:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:u})},s=()=>{const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:u},n=Ke(this.video),o=(u,d)=>this.subscription.add(u.subscribe(d,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==V.Applying)&&(this.videoState.getState()===U.PLAYING||this.videoState.getState()===U.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(rt(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(r.map(u=>u.map(({track:d})=>d)))}),o(zt(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(U.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(u=>{this.buffer.fill(),e.currentBuffer$.next(u)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:u,message:d,thrown:c})=>({id:`DashLite_${u}`,category:r.ErrorCategory.WTF,message:d,thrown:c}))).subscribe(this.params.output.error$)).add(r.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{const u=this.currentRepresentation$.getValue(),d=this.representations$.getValue(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState()?.id,l=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),p=s();c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to);let g;if(!p&&r.isNonNullable(h))g=h;else{const y=ke(this.video.buffered,this.video.currentTime*1e3),b=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,k=Math.min(y/b,1);g=Tt(d.map(({track:m})=>m),{container:f,throughput:l,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:k,playbackRate:this.video.playbackRate,current:d.find(({representation:m})=>m===u)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const A=t.autoVideoTrackLimits.getTransition();A&&e.autoVideoTrackLimits$.next(A.to)}return r.isNonNullable(g)?d.find(({track:y})=>y.id===g)?.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(u=>u.to===U.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(U.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((u,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?u.height<=d.height:u===d)).subscribe(u=>{const d=ke(this.video.buffered,this.video.currentTime*1e3),c=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||c<=.5||!s())&&(this.dash.setQualityByRepresentation(u,!0),this.params.output.hostname$.next(ye(u.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(u=>{const{type:d,reused:c}=Li(u);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(c)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(u=>this.params.dependencies.throughputEstimator.addRawRtt(u))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return r.assertNever(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const n=s.name??s.id??s.height.toString(10),o=(s.name&&It(s.name))??r.videoSizeToQuality(s),u=s.bandwidth/1e3,d={width:s.width,height:s.height},c=s.fps;if(!o)continue;const h={id:n,quality:o,bitrate:u,size:d,fps:c};i.push({track:h,representation:s})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),t?.length>0){const s=[];for(const n of t){const o=n.id||`${n.language}_${Date.now()}`;s.push({id:o,type:"internal",url:n.url||"",language:n.language,isAuto:n.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(U.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return r.assertNonNullable(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=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!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(U.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!t)switch(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&Ia.includes(e)&&this.seek(n.position,n.forcePrecise),e){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_LOADED),this.prepare();return;case U.MANIFEST_LOADED:this.videoState.startTransitionTo(U.INITIAL_REPRESENTATION_SELECTED);return;case U.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(U.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case U.METADATA_LOADED:this.videoState.startTransitionTo(U.READY),this.dash.updateRefsForCurrentTime();return;case U.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed());return;case U.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(U.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}}var fe;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(fe||(fe={}));var ri;(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"})(ri||(ri={}));var xe;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(xe||(xe={}));var H;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(H||(H={}));var Dt;(function(a){a.MP4="mp4",a.WEBM="webm"})(Dt||(Dt={}));var ni;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(ni||(ni={}));var Z;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Z||(Z={}));class Oi{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 s=0,n=i.length;s<n;s++)if(i[s].callback===t){i.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let s=0,n=i.length;s<n;s++){const o=i[s];try{o.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class ps extends Oi{constructor(){super(),this.listeners||Oi.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 ms=class{constructor(){Object.defineProperty(this,"signal",{value:new ps,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&&(ms.prototype[Symbol.toStringTag]="AbortController",ps.prototype[Symbol.toStringTag]="AbortSignal");function gs(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 _a(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=a;if(!gs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(c,h){let l;h&&h.signal&&(l=h.signal,delete h.signal);const f=new t(c,h);return l&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,c)=>{const h=n&&n.prototype.isPrototypeOf(d)?d.signal:c?c.signal:void 0;if(h){let l;try{l=new DOMException("Aborted","AbortError")}catch{l=new Error("Aborted"),l.name="AbortError"}if(h.aborted)return Promise.reject(l);const f=new Promise((p,g)=>{h.addEventListener("abort",()=>g(l),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([f,o(d,c)])}return o(d,c)},Request:n}}const gi=gs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),bs=gi?_a({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,yt=gi?bs.fetch:window.fetch;gi?bs.Request:window.Request;const Ie=gi?ms:window.AbortController;var Ct=(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 Ba=(a,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-s-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},Ma=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",oi=Ma?Ba:window.requestIdleCallback,Va=16;let Ss=!1;try{Ss=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Va}catch(a){console.error(a)}let Fa=class{bufferFull$=new r.Subject;error$=new r.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 s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Ss&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!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:r.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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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:r.assertNever(t)}}};var ui=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};let Ze=class{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}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}},ys=class extends Ze{},Oa=class extends Ze{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}},Ua=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},Ha=class extends Ze{data;constructor(e){super(e),this.data=this.content}},Jt=class extends Ze{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},ja=class extends Jt{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const u=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}},Ya=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},Ga=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}};var bt;(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"})(bt||(bt={}));let za=class extends Jt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=bt.MONOSCOPIC;break;case 1:this.stereoMode=bt.TOP_BOTTOM;break;case 2:this.stereoMode=bt.LEFT_RIGHT;break;case 3:this.stereoMode=bt.STEREO_CUSTOM;break;case 4:this.stereoMode=bt.RIGHT_LEFT;break}this.cursor+=1}},qa=class extends Jt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},Wa=class extends Jt{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},Qa=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},Ja=class extends Jt{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}},Xa=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}},Ka=class extends Ze{parseChildrenBoxes(){return Nt(this.content)}};const Za={ftyp:Oa,moov:Ua,mdat:Ha,sidx:ja,trak:Ya,mdia:Qa,tkhd:Ja,minf:Xa,sv3d:Ga,st3d:za,prhd:qa,proj:Ka,equi:Wa,unknown:ys};let er=class{createBox(e,t){const i=Za[e];return i?new i(t):new ys(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return bi.createBox(i,new DataView(e.buffer,e.byteOffset))}};const bi=new er;function Ht(a,e){const t=new TextDecoder("ascii");let i=a.byteOffset,s=[];for(;i<a.byteLength;){const n=t.decode(new DataView(a.buffer,i,1));if(n===e[s.length]?s.push(n):s=[],s.length===4&&s.join("")===e){const u=new DataView(a.buffer,i-7,4).getUint32(0);return i-7+u>a.byteLength?null:bi.createBox(e,new DataView(a.buffer,i-7))}i++}return null}function tr(a,e){const t=[];let i=0;for(;i<a.byteLength;){const s=Ht(new DataView(a.buffer,a.byteOffset+i,a.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function Nt(a){const e=[];let t=0;for(;t<a.byteLength;){const i=bi.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const ir=new TextDecoder("ascii"),sr=a=>ir.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ar=a=>{const e=bi.createFromView(a);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,u={status:H.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,u})},rr=a=>{const e=tr(a,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(a.buffer,a.byteOffset,t)}return null},nr=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ht(a,"sv3d")){e.is3dVideo=!0;const i=Ht(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=Ht(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=Ht(a,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},or={validateData:sr,parseInit:nr,getIndexRange:()=>{},parseSegments:ar,parseFeedableSegmentChunk:rr};var v;(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"})(v||(v={}));var P;(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"})(P||(P={}));const Ui={[v.EBML]:{type:P.Master},[v.EBMLVersion]:{type:P.UnsignedInteger},[v.EBMLReadVersion]:{type:P.UnsignedInteger},[v.EBMLMaxIDLength]:{type:P.UnsignedInteger},[v.EBMLMaxSizeLength]:{type:P.UnsignedInteger},[v.DocType]:{type:P.String},[v.DocTypeVersion]:{type:P.UnsignedInteger},[v.DocTypeReadVersion]:{type:P.UnsignedInteger},[v.Void]:{type:P.Binary},[v.Segment]:{type:P.Master},[v.SeekHead]:{type:P.Master},[v.Seek]:{type:P.Master},[v.SeekID]:{type:P.Binary},[v.SeekPosition]:{type:P.UnsignedInteger},[v.Info]:{type:P.Master},[v.TimestampScale]:{type:P.UnsignedInteger},[v.Duration]:{type:P.Float},[v.Tracks]:{type:P.Master},[v.TrackEntry]:{type:P.Master},[v.Video]:{type:P.Master},[v.Projection]:{type:P.Master},[v.ProjectionType]:{type:P.UnsignedInteger},[v.ProjectionPrivate]:{type:P.Master},[v.Chapters]:{type:P.Master},[v.Cluster]:{type:P.Master},[v.Timestamp]:{type:P.UnsignedInteger},[v.SilentTracks]:{type:P.Master},[v.SilentTrackNumber]:{type:P.UnsignedInteger},[v.Position]:{type:P.UnsignedInteger},[v.PrevSize]:{type:P.UnsignedInteger},[v.SimpleBlock]:{type:P.Binary},[v.BlockGroup]:{type:P.Master},[v.EncryptedBlock]:{type:P.Binary},[v.Attachments]:{type:P.Master},[v.Tags]:{type:P.Master},[v.Cues]:{type:P.Master},[v.CuePoint]:{type:P.Master},[v.CueTime]:{type:P.UnsignedInteger},[v.CueTrackPositions]:{type:P.Master},[v.CueTrack]:{type:P.UnsignedInteger},[v.CueClusterPosition]:{type:P.UnsignedInteger},[v.CueRelativePosition]:{type:P.UnsignedInteger},[v.CueDuration]:{type:P.UnsignedInteger},[v.CueBlockNumber]:{type:P.UnsignedInteger},[v.CueCodecState]:{type:P.UnsignedInteger},[v.CueReference]:{type:P.Master},[v.CueRefTime]:{type:P.UnsignedInteger}},Ts=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=ci(a,t),s=i in Ui,n=s?Ui[i].type:P.Binary,o=a.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(a.buffer,a.byteOffset+t+1,u-1),c=o&255>>u,h=ci(d),l=c*2**((u-1)*8)+h,f=t+u;let p;return f+l>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,l),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+l,value:p,valueSize:l}},ci=(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},ze=(a,e)=>{switch(e){case P.SignedInteger:return a.getInt8(0);case P.UnsignedInteger:return ci(a);case P.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case P.String:return new TextDecoder("ascii").decode(a);case P.UTF8:return new TextDecoder("utf-8").decode(a);case P.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case P.Master:return a;case P.Binary:return a;default:r.assertNever(e)}},Lt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=Ts(i);if(!e(s))return;s.type===P.Master&&Lt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},ur=a=>{if(a.getUint32(0)!==v.EBML)return!1;let e,t,i;const s=Ts(a);return Lt(s.value,({tag:n,type:o,value:u})=>(n===v.EBMLReadVersion?e=ze(u,o):n===v.DocType?t=ze(u,o):n===v.DocTypeReadVersion&&(i=ze(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},vs=[v.Info,v.SeekHead,v.Tracks,v.TrackEntry,v.Video,v.Projection,v.ProjectionType,v.ProjectionPrivate,v.Chapters,v.Cluster,v.Cues,v.Attachments,v.Tags],cr=[v.Timestamp,v.SilentTracks,v.SilentTrackNumber,v.Position,v.PrevSize,v.SimpleBlock,v.BlockGroup,v.EncryptedBlock],dr=a=>{let e,t,i,s,n=!1,o=!1,u=!1,d,c,h=!1;const l=0;return Lt(a,({tag:f,type:p,value:g,valueSize:y})=>{if(f===v.SeekID){const b=ze(g,p);c=ci(b)}else f!==v.SeekPosition&&(c=void 0);return f===v.Segment?(e=g.byteOffset,t=g.byteOffset+y):f===v.Info?n=!0:f===v.SeekHead?o=!0:f===v.TimestampScale?i=ze(g,p):f===v.Duration?s=ze(g,p):f===v.SeekPosition&&c===v.Cues?d=ze(g,p):f===v.Tracks?Lt(g,({tag:b,type:k,value:A})=>b===v.ProjectionType?(h=ze(A,k)===1,!1):!0):n&&o&&vs.includes(f)&&(u=!0),!u}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(s,"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(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},lr=a=>{if(r.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hr=(a,e)=>{let t=!1,i=!1;const s=u=>r.isNonNullable(u.time)&&r.isNonNullable(u.position),n=[];let o;return Lt(a,({tag:u,type:d,value:c})=>{switch(u){case v.Cues:t=!0;break;case v.CuePoint:o&&s(o)&&n.push(o),o={};break;case v.CueTime:o&&(o.time=ze(c,d));break;case v.CueTrackPositions:break;case v.CueClusterPosition:o&&(o.position=ze(c,d));break;default:t&&vs.includes(u)&&(i=!0)}return!(t&&i)}),o&&s(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:h}=u,l=n[d+1];return{status:H.NONE,time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},fr=a=>{let e=0,t=!1;try{Lt(a,i=>i.tag===v.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):cr.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[v.SimpleBlock,v.BlockGroup,v.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},pr={validateData:ur,parseInit:dr,getIndexRange:lr,parseSegments:hr,parseFeedableSegmentChunk:fr},Es=1e4,mr=3e4,gr=5e3,br=Es,Sr=({id:a,width:e,height:t,bitrate:i,fps:s,quality:n})=>{const o=(n?It(n):void 0)??r.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:s}},yr=({id:a,bitrate:e})=>({id:a,bitrate:e}),Tr=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},vr=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),ti=a=>{const e=[];let t=0,i=a.length-1;for(;t<Es&&i>=0;)e.unshift(a[i]),t+=a[i].time.to-a[i].time.from,i--;return e};let Hi=class{onLastSegment$=new r.ValueSubject(!1);fullyBuffered$=new r.ValueSubject(!1);playingRepresentation$=new r.ValueSubject(void 0);playingRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;gaps=[];isSeekingLive=!1;subscription=new r.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Ie;destroyAbortController=new Ie;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,s,{fetcher:n,tuning:o,getCurrentPosition:u,compatibilityMode:d=!1,manifest:c}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.isLive=!!c?.dynamic,this.container=i,i){case Dt.MP4:this.containerParser=or;break;case Dt.WEBM:this.containerParser=pr;break;default:r.assertNever(i)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=r.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);r.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 Fa(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),n=this.parsedInitData.get(t.id);r.assertNonNullable(i,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=r.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);r.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(r.isNullable(s)||r.isNullable(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),r.assertNonNullable(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const n=this.getCurrentPosition();r.isNonNullable(n)&&(this.searchGaps(i,t),this.maintain(n))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=ke(this.sourceBuffer.buffered,e),l=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){const c=ke(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(u.includes(s))c="high";else{const h=u.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===H.FED&&!u.length&&ke(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=i.at(-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const s of e)s.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from}),i=s.time.to;r.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.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=r.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const u of this.representations.keys()){const d=e.find(l=>l.id===u);d&&this.representations.set(u,d);const c=this.representations.get(u);if(!c)return;const h=ti(c.segmentReference.segments);this.segments.set(c.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);r.assertNonNullable(i);const s=ti(i.segmentReference.segments),n=this.initData.get(i.id);if(r.assertNonNullable(n,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),!(n instanceof ArrayBuffer))return;const o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t)return;const i=t.segmentReference.segments.map(u=>({...u,status:H.NONE,size:void 0})),s=this.segments.get(t.id)??[],n=s.at(-1)?.time.to??0,o=i?.findIndex(u=>Math.round(n)>=Math.round(u.time.from)&&Math.round(n)<=Math.round(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const u=ti(i);this.segments.set(t.id,[...u])}else{const u=i.slice(o+1);this.segments.set(t.id,[...s,...u])}}}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(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:l,time:{from:f,to:p}},g)=>{const y=f<=i&&p>=i,b=f>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&f<=i+k||p<=i+k;return(l===H.NONE||l===H.PARTIALLY_EJECTED&&b&&A&&this.sourceBuffer&&!Ct(this.sourceBuffer.buffered,i))&&b&&A});if(s===-1)return[];if(t!==xe.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<n.length&&(o<=c||u<=h);l++){const f=n[l];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,n,o=e;const{type:u}=t.segmentReference;switch(u){case xe.BYTE_RANGE:{s=t.segmentReference.url,n={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case xe.TEMPLATE:{const c=e.at(0);s=new URL(c.url,t.segmentReference.baseUrl).toString(),o=[c];break}default:r.assertNever(u)}for(const c of o)c.status=H.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await r.abortable(d,async function*(){const c=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,c))}.bind(this))(),d.aborted))for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(c,h)=>{if(!d.aborted)try{this.onSomeDataLoaded(c,t.id,n?n.from:0,h,d)}catch(l){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:d,priority:i}).then(()=>this.failedDownloads=0,c=>{if(c.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(c)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(i)&&(t=ke(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,s,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},u=l=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),l.segment.status=H.FED,"size"in l.segment&&(l.segment.size=l.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const p of this.segments.get(f.id)??[])p.status===H.FED&&p.time.from===l.segment.time.from&&p.time.to===l.segment.time.to&&(p.status=H.NONE);this.activeSegments.delete(l),this.detectGapsWhenIdle(t,[l.segment])},d=this.representations.get(t);if(!d)return;const c=d.segmentReference.type,h=e.byteLength;for(const l of this.activeSegments){const{segment:f}=l,p=c===xe.BYTE_RANGE,g=p?f.byte.to-f.byte.from+1:h;if(l.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const b=p?f.byte.from-i:0,k=p?f.byte.to-i:e.byteLength,A=b<s,m=k<=s;if(f.status===H.DOWNLOADING&&A&&m){f.status=H.DOWNLOADED,this.activeSegments.delete(l);const T=new DataView(e.buffer,e.byteOffset+b,g);this.sourceBufferTaskQueue.append(T,n).then($=>$&&!n.aborted?u(l):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&A&&(l.loadedBytes=Math.min(g,s-b),l.loadedBytes>l.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),$=l.loadedBytes===g?T:this.containerParser.parseFeedableSegmentChunk(T);$?.byteLength&&(f.status=H.PARTIALLY_FED,l.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,n).then(R=>{if(n.aborted)o();else if(R)l.fedBytes+=$.byteLength,l.fedBytes===g&&u(l);else{if(l.feedingBytes<g)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=oi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async u=>{if(!u)return;const{init:d,dataView:c,segments:h}=u,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,this.isLive?ti(h):h),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const h="size"in c?c.size??0:c.byte.to-c.byte.from;s+=h};for(const c of this.segments.values())for(const h of c){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===H.FED&&d(h)}if(u=isFinite(n)&&isFinite(o),!u){s=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const h of c){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===H.FED&&d(h)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const h=this.sourceBuffer.buffered.start(c)*1e3,l=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===H.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(l)){n=h,o=l;break}}if(u=isFinite(n)&&isFinite(o),!u&&i){s=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+c&&l.status===H.FED&&d(l)}return u=isFinite(n)&&isFinite(o),u?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 s={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,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){s=void 0;break}u>i.time.from&&u<i.time.to&&(s.from=u),o<i.time.to&&o>i.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=oi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:n})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:n}=s;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),u=Math.ceil(s.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=u),c=e.filter(h=>o>=h.from-t&&o<=h.to+t||u>=h.from-t&&u<=h.to+t);d||(c.length===1?s.status=H.PARTIALLY_EJECTED:s.status=H.NONE)}}};var At;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(At||(At={}));let Er=class{throughputEstimator;requestQuic;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);abortAllController=new Ie;subscription=new r.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}=Li(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=r.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ct(t));const i=yield yt(t,{signal:this.abortAllController.signal}).catch(Vt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=r.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?At.HEADER:At.PARAM,range:i,onProgress:s,priority:n="auto",signal:o,measureThroughput:u=!0}={}){let d=e;const c=new Headers;if(i)switch(t){case At.HEADER:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case At.PARAM:{const S=new URL(d,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),d=S.toString();break}default:r.assertNever(t)}this.requestQuic&&(d=ct(d));let h=this.abortAllController.signal,l;if(o){const S=new Ie;if(l=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(o,"abort")).subscribe(()=>{try{S.abort()}catch(L){Vt(L)}}),this.abortAllController.signal.aborted||o.aborted)try{S.abort()}catch(L){Vt(L)}h=S.signal}const f=r.now(),p=yield yt(d,{priority:n,headers:c,signal:h}).catch(Vt),g=r.now();if(this.throughputEstimator?.addRawRtt(g-f),!p)return l?.unsubscribe(),null;if(!p.ok||!p.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const y=parseInt(p.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!y){const S=yield p.arrayBuffer();return this.throughputEstimator?.addRawSpeed(S.byteLength,r.now()-g),s?.(new DataView(S),S.byteLength),l?.unsubscribe(),S}if(!s&&!u)return l?.unsubscribe(),p.arrayBuffer();const[b,k]=p.body.tee(),A=b.getReader();u&&this.throughputEstimator?.trackStream(k);let m=0;const T=new ArrayBuffer(y),$=new Uint8Array(T),R=new DataView(T);let _=!1;const C=S=>{l?.unsubscribe(),_=!0,Vt(S)},I=r.abortable(h,async function*({done:S,value:L}){if(m===0&&this.lastRequestFirstBytes$.next(r.now()-f),h.aborted){l?.unsubscribe();return}!S&&L&&($.set(L,m),m+=L.byteLength,s?.(R,m),yield A?.read().then(I,C))}.bind(this));return yield A?.read().then(I,C),l?.unsubscribe(),_?null:T}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case xe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case xe.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:r.assertNever(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==xe.BYTE_RANGE)return null;const{from:s,to:n}=e.initRange;let o=s,u=n,d=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,s),u=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:u},priority:i,measureThroughput:!1});if(!l)return null;const f=new DataView(l,s-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),g=e.indexRange??t.getIndexRange(p);if(!g)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,g.from-o,g.to-g.from+1);else{const k=yield this.fetch(e.url,{range:g,priority:i,measureThroughput:!1});if(!k)return null;y=new DataView(k)}const b=t.parseSegments(y,p,g);return{init:p,dataView:new DataView(l),segments:b}}.bind(this));fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==xe.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(o=>({...o,status:H.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))};const Vt=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},ji=a=>{if(!a.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},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),s=i?.[1]==="-"?-1:1,n={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},yi=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(i)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>r.isNullable(n)?u:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},kr=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],u=o.children,d=n.getAttribute("type")==="dynamic",c=n.getAttribute("availabilityStartTime"),h=c?new Date(c).getTime():void 0;let l;const f=n.getAttribute("mediaPresentationDuration"),p=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)l=ji(f);else if(p){const m=ji(p);r.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let b=0;const k=n.getAttribute("profiles")?.split(",")??[],A=k.includes(ri.WEBM_AS_IN_FFMPEG)||k.includes(ri.WEBM_AS_IN_SPEC)?Dt.WEBM:Dt.MP4;for(const m of u){const T=m.getAttribute("mimeType"),$=m.getAttribute("codecs"),R=m.getAttribute("contentType")??T?.split("/")[0],_=m.getAttribute("profiles")?.split(",")??[],C=m.querySelectorAll("Representation"),I=m.querySelector("SegmentTemplate");if(R===fe.TEXT){for(const S of C){const L=S.getAttribute("id")||"",N=m.getAttribute("lang"),j=S.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(j,e).toString(),ne=L.includes("_auto");s[fe.TEXT].push({id:L,lang:N,isAuto:ne,kind:fe.TEXT,url:ie})}continue}for(const S of C){const L=S.getAttribute("mimeType")??T,N=S.getAttribute("codecs")??$??"",j=S.getAttribute("contentType")??L?.split("/")[0]??R,ie=m.getAttribute("profiles")?.split(",")??[],ne=parseInt(S.getAttribute("width")??"",10),x=parseInt(S.getAttribute("height")??"",10),G=parseInt(S.getAttribute("bandwidth")??"",10)/1e3,K=S.getAttribute("frameRate")??"",oe=S.getAttribute("quality")??void 0,me=K?mi(K):void 0,Oe=S.getAttribute("id")??(b++).toString(10),_t=j==="video"?`${x}p`:j==="audio"?`${G}Kbps`:N,vt=`${Oe}@${_t}`,z=S.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(z,e).toString(),Te=[...k,..._,...ie];let de;const et=S.querySelector("SegmentBase"),se=S.querySelector("SegmentTemplate")??I;if(et){const ue=S.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[le,Ue]=ue.split("-").map(we=>parseInt(we,10)),ve={from:le,to:Ue},_e=S.querySelector("SegmentBase")?.getAttribute("indexRange"),[ht,tt]=_e?_e.split("-").map(we=>parseInt(we,10)):[],Be=_e?{from:ht,to:tt}:void 0;de={type:xe.BYTE_RANGE,url:ce,initRange:ve,indexRange:Be}}else if(se){const ue={representationId:S.getAttribute("id")??void 0,bandwidth:S.getAttribute("bandwidth")??void 0},le=parseInt(se.getAttribute("timescale")??"",10),Ue=se.getAttribute("initialization")??"",ve=se.getAttribute("media"),_e=parseInt(se.getAttribute("startNumber")??"",10)??1,ht=yi(Ue,ue);if(!ve)throw new ReferenceError("No media attribute in SegmentTemplate");const tt=se.querySelectorAll("SegmentTimeline S")??[],Be=[];let we=0;if(tt.length){let ft=_e,Ae=0;for(const pt of tt){const Pe=parseInt(pt.getAttribute("d")??"",10),ae=parseInt(pt.getAttribute("r")??"",10)||0,Me=parseInt(pt.getAttribute("t")??"",10);Ae=Number.isFinite(Me)?Me:Ae;const Ee=Pe/le*1e3,He=Ae/le*1e3;for(let it=0;it<ae+1;it++){const Bt=yi(ve,{...ue,segmentNumber:ft.toString(10),segmentTime:(Ae+it*Pe).toString(10)}),Xt=(He||0)+it*Ee,Et=Xt+Ee;ft++,Be.push({time:{from:Xt,to:Et},url:Bt})}Ae+=(ae+1)*Pe,we+=(ae+1)*Ee}}else if(r.isNonNullable(l)){const Ae=parseInt(se.getAttribute("duration")??"",10)/le*1e3,pt=Math.ceil(l/Ae);let Pe=0;for(let ae=1;ae<pt;ae++){const Me=yi(ve,{...ue,segmentNumber:ae.toString(10),segmentTime:Pe.toString(10)});Be.push({time:{from:Pe,to:Pe+Ae},url:Me}),Pe+=Ae}}de={type:xe.TEMPLATE,baseUrl:ce,initUrl:ht,totalSegmentsDurationMs:we,segments:Be}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!L)continue;const $e={video:fe.VIDEO,audio:fe.AUDIO,text:fe.TEXT}[j];$e&&s[$e].push({id:vt,kind:$e,segmentReference:de,profiles:Te,duration:l,bitrate:G,mime:L,codecs:N,width:ne,height:x,fps:me,quality:oe})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:A,representations:s}},ki=1e3,Yi=["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 $r=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new r.Subscription;representationSubscription=new r.Subscription;fetcher;state$=new q(Ce.NONE);currentVideoRepresentation$=new r.ValueSubject(void 0);currentVideoRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);isLive$=new r.ValueSubject(!1);liveDuration$=new r.ValueSubject(0);liveAvailabilityStartTime$=new r.ValueSubject(void 0);bufferLength$=new r.ValueSubject(0);liveLoadBufferLength$=new r.ValueSubject(0);forceEnded$=new r.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Ie;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Er({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=r.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Se(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:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=r.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=kr(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||s===fe.TEXT);return this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,n])=>[s,n.filter(i)]))}}.bind(this));async seekLive(e){r.assertNonNullable(this.element),this.manifestUrlString=Se(this.manifestUrlString,e,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=r.abortable(this.destroyController.signal,async function*(e,t){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ce.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Hi(fe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(t)&&(this.audioBufferManager=new Hi(fe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(r.interval(ki).subscribe(o=>{if(this.element?.paused){const u=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=Se(this.manifestUrlString,u+1e3,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Yi.map(o=>r.fromEvent(this.element,o))).pipe(r.throttle(ki),r.map(o=>this.element?ke(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(u=>{let d=0;if(u){const c=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-c}this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async u=>{r.assertNonNullable(this.element);const d=this.element.playbackRate,c=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P),h=mr*d,l=br*d,f=gr*d;o=u>o?u:o;const p=c===0&&u<f,g=c!==0&&u<h+f&&u>=h,y=c!==0&&u<h;if(y||g){const b=o-(h+l),k=Math.trunc(c+b/d);let A;u?k>0?A=k:A=0:A=c,this.manifestUrlString=Se(this.manifestUrlString,A,X.DASH_CMAF_OFFSET_P)}(p||y||g)&&(await this.updateLive(),o=0)}))}const s=r.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=r.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:s,someBufferEnded:n}).pipe(r.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(o=>!o.updating))try{this.source?.endOfStream()}catch(o){this.error$.next({id:"EndOfStream",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(r.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.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(){r.assertNonNullable(this.element),this.state$.setState(Ce.RUNNING),this.subscription.add(r.merge(...Yi.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[fe.VIDEO]:this.videoBufferManager,[fe.AUDIO]:this.audioBufferManager,[fe.TEXT]:null}[e]?.switchTo(t)}seek(e,t){r.assertNonNullable(this.element),r.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),Ct(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(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}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=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};class wr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Ar{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 s=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:s,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 s=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>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 Pr=`#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;}`,Dr=`#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 ks{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 s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new Pr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Dr(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"),s=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(s,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(Cr,this.gl.VERTEX_SHADER),i=this.createShader(Lr,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 s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/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,s=this.camera.fov.y/180/2,n=e-i,o=t-s,u=e+i,d=t-s,c=e+i,h=t+s,l=e-i,f=t+s;return[n,o,u,d,c,h,l,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}}let $s=class{scene3D;subscription=new r.Subscription;videoState=new q(Z.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(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(Se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new wr({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=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,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(r.map(c=>c.map(({track:h})=>h)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===De.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=vr(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=Tr(b);if(k){h.push({track:k,representation:b});const w=!this.params.tuning.isAudioDisabled&&Er(f,p,b);w&&this.audioRepresentations.set(b.id,w)}}this.videoTracks$.next(h);for(const b of g){const k=kr(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.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 y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===De.REPRESENTATIOS_READY&&(this.videoState.setState(Z.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==De.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(he.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(he.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=Ee(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Z.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.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(Z.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Z.STOPPED:this.videoState.startTransitionTo(Z.READY),this.prepare();return;case Z.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Z.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.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 r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(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(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Z.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:r.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),Xe(this.video)}},xr=class extends $s{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)}};var fe;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(fe||(fe={}));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 di;(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"})(di||(di={}));var xe;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(xe||(xe={}));var M;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(M||(M={}));var xt;(function(a){a.MP4="mp4",a.WEBM="webm"})(xt||(xt={}));var li;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(li||(li={}));var ee;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ee||(ee={}));let As=!1;try{As=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Rr{bufferFull$=new r.Subject;error$=new r.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 s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;As&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!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:r.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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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:r.assertNever(t)}}}class Ie{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}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 ws extends Ie{}class Ir extends Ie{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Nr extends Ie{parseChildrenBoxes(){return lt(this.content)}}class _r extends Ie{parseChildrenBoxes(){return lt(this.content)}}class Br extends Ie{data;constructor(e){super(e),this.data=this.content}}class ot extends Ie{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Mr extends ot{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const u=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class Vr extends Ie{parseChildrenBoxes(){return lt(this.content)}}class Fr extends Ie{parseChildrenBoxes(){return lt(this.content)}}var St;(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"})(St||(St={}));class Or extends ot{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=St.MONOSCOPIC;break;case 1:this.stereoMode=St.TOP_BOTTOM;break;case 2:this.stereoMode=St.LEFT_RIGHT;break;case 3:this.stereoMode=St.STEREO_CUSTOM;break;case 4:this.stereoMode=St.RIGHT_LEFT;break}this.cursor+=1}}class Ur extends ot{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Hr extends ot{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class jr extends Ie{parseChildrenBoxes(){return lt(this.content)}}class Yr extends ot{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Gr extends Ie{parseChildrenBoxes(){return lt(this.content)}}class zr extends Ie{parseChildrenBoxes(){return lt(this.content)}}class qr extends ot{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Wr extends Ie{parseChildrenBoxes(){return lt(this.content)}}class Qr extends ot{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Jr extends ot{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Xr extends ot{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Kr={ftyp:Ir,moov:Nr,moof:_r,mdat:Br,sidx:Mr,trak:Vr,mdia:jr,mfhd:qr,tkhd:Yr,traf:Wr,tfhd:Qr,tfdt:Jr,trun:Xr,minf:Gr,sv3d:Fr,st3d:Or,prhd:Ur,proj:zr,equi:Hr,unknown:ws};class Zr{createBox(e,t){const i=Kr[e];return i?new i(t):new ws(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Si.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Si=new Zr;function jt(a,e){const t=new Uint8Array(a.buffer),i=e.split("").map(o=>o.charCodeAt(0));let s=a.byteOffset,n=[];for(;s<t.byteLength;){if(t[s]===i[n.length]?n.push(t[s]):n=[],n.length===4){const u=new DataView(a.buffer,s-7,4).getUint32(0);return s-7+u>a.buffer.byteLength?null:Si.createBox(e,new DataView(a.buffer,s-7))}s++}return null}function $i(a,e){const t=[];let i=a.byteOffset;for(;i<a.buffer.byteLength;){const s=jt(new DataView(a.buffer,i,a.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function lt(a){const e=[];let t=0;for(;t<a.byteLength;){const i=Si.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const en=new TextDecoder("ascii"),tn=a=>en.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",sn=a=>{const e=Si.createFromView(a);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,u={status:M.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,u})},an=a=>{const e=$i(a,"mdat"),t=$i(a,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],n=i.source.byteOffset,u=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(a.buffer,n,u)},rn=(a,e)=>{const t=$i(a,"traf"),i=t[t.length-1].children.find(d=>d.type==="tfhd"),s=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,c)=>d+c,0):o=i.defaultSampleDuration*n.sampleCount,(Number(s.baseMediaDecodeTime)+o)/e*1e3},nn=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(jt(a,"sv3d")){e.is3dVideo=!0;const i=jt(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=jt(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=jt(a,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},on={validateData:tn,parseInit:nn,getIndexRange:()=>{},parseSegments:sn,parseFeedableSegmentChunk:an,getSegmentEndTime:rn};var v;(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"})(v||(v={}));var D;(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"})(D||(D={}));const Gi={[v.EBML]:{type:D.Master},[v.EBMLVersion]:{type:D.UnsignedInteger},[v.EBMLReadVersion]:{type:D.UnsignedInteger},[v.EBMLMaxIDLength]:{type:D.UnsignedInteger},[v.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[v.DocType]:{type:D.String},[v.DocTypeVersion]:{type:D.UnsignedInteger},[v.DocTypeReadVersion]:{type:D.UnsignedInteger},[v.Void]:{type:D.Binary},[v.Segment]:{type:D.Master},[v.SeekHead]:{type:D.Master},[v.Seek]:{type:D.Master},[v.SeekID]:{type:D.Binary},[v.SeekPosition]:{type:D.UnsignedInteger},[v.Info]:{type:D.Master},[v.TimestampScale]:{type:D.UnsignedInteger},[v.Duration]:{type:D.Float},[v.Tracks]:{type:D.Master},[v.TrackEntry]:{type:D.Master},[v.Video]:{type:D.Master},[v.Projection]:{type:D.Master},[v.ProjectionType]:{type:D.UnsignedInteger},[v.ProjectionPrivate]:{type:D.Master},[v.Chapters]:{type:D.Master},[v.Cluster]:{type:D.Master},[v.Timestamp]:{type:D.UnsignedInteger},[v.SilentTracks]:{type:D.Master},[v.SilentTrackNumber]:{type:D.UnsignedInteger},[v.Position]:{type:D.UnsignedInteger},[v.PrevSize]:{type:D.UnsignedInteger},[v.SimpleBlock]:{type:D.Binary},[v.BlockGroup]:{type:D.Master},[v.EncryptedBlock]:{type:D.Binary},[v.Attachments]:{type:D.Master},[v.Tags]:{type:D.Master},[v.Cues]:{type:D.Master},[v.CuePoint]:{type:D.Master},[v.CueTime]:{type:D.UnsignedInteger},[v.CueTrackPositions]:{type:D.Master},[v.CueTrack]:{type:D.UnsignedInteger},[v.CueClusterPosition]:{type:D.UnsignedInteger},[v.CueRelativePosition]:{type:D.UnsignedInteger},[v.CueDuration]:{type:D.UnsignedInteger},[v.CueBlockNumber]:{type:D.UnsignedInteger},[v.CueCodecState]:{type:D.UnsignedInteger},[v.CueReference]:{type:D.Master},[v.CueRefTime]:{type:D.UnsignedInteger}},Ps=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=hi(a,t),s=i in Gi,n=s?Gi[i].type:D.Binary,o=a.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(a.buffer,a.byteOffset+t+1,u-1),c=o&255>>u,h=hi(d),l=c*2**((u-1)*8)+h,f=t+u;let p;return f+l>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,l),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+l,value:p,valueSize:l}},hi=(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},qe=(a,e)=>{switch(e){case D.SignedInteger:return a.getInt8(0);case D.UnsignedInteger:return hi(a);case D.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(a);case D.UTF8:return new TextDecoder("utf-8").decode(a);case D.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case D.Master:return a;case D.Binary:return a;default:r.assertNever(e)}},Rt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=Ps(i);if(!e(s))return;s.type===D.Master&&Rt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},un=a=>{if(a.getUint32(0)!==v.EBML)return!1;let e,t,i;const s=Ps(a);return Rt(s.value,({tag:n,type:o,value:u})=>(n===v.EBMLReadVersion?e=qe(u,o):n===v.DocType?t=qe(u,o):n===v.DocTypeReadVersion&&(i=qe(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ds=[v.Info,v.SeekHead,v.Tracks,v.TrackEntry,v.Video,v.Projection,v.ProjectionType,v.ProjectionPrivate,v.Chapters,v.Cluster,v.Cues,v.Attachments,v.Tags],cn=[v.Timestamp,v.SilentTracks,v.SilentTrackNumber,v.Position,v.PrevSize,v.SimpleBlock,v.BlockGroup,v.EncryptedBlock],dn=a=>{let e,t,i,s,n=!1,o=!1,u=!1,d,c,h=!1;const l=0;return Rt(a,({tag:f,type:p,value:g,valueSize:y})=>{if(f===v.SeekID){const b=qe(g,p);c=hi(b)}else f!==v.SeekPosition&&(c=void 0);return f===v.Segment?(e=g.byteOffset,t=g.byteOffset+y):f===v.Info?n=!0:f===v.SeekHead?o=!0:f===v.TimestampScale?i=qe(g,p):f===v.Duration?s=qe(g,p):f===v.SeekPosition&&c===v.Cues?d=qe(g,p):f===v.Tracks?Rt(g,({tag:b,type:k,value:w})=>b===v.ProjectionType?(h=qe(w,k)===1,!1):!0):n&&o&&Ds.includes(f)&&(u=!0),!u}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(s,"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(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ln=a=>{if(r.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hn=(a,e)=>{let t=!1,i=!1;const s=u=>r.isNonNullable(u.time)&&r.isNonNullable(u.position),n=[];let o;return Rt(a,({tag:u,type:d,value:c})=>{switch(u){case v.Cues:t=!0;break;case v.CuePoint:o&&s(o)&&n.push(o),o={};break;case v.CueTime:o&&(o.time=qe(c,d));break;case v.CueTrackPositions:break;case v.CueClusterPosition:o&&(o.position=qe(c,d));break;default:t&&Ds.includes(u)&&(i=!0)}return!(t&&i)}),o&&s(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:h}=u,l=n[d+1];return{status:M.NONE,time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},fn=a=>{let e=0,t=!1;try{Rt(a,i=>i.tag===v.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):cn.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[v.SimpleBlock,v.BlockGroup,v.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},pn={validateData:un,parseInit:dn,getIndexRange:ln,parseSegments:hn,parseFeedableSegmentChunk:fn},zi=a=>{if(!a.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},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),s=i?.[1]==="-"?-1:1,n={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},At=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(i)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>r.isNullable(n)?u:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},mn=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],u=o.children,d=n.getAttribute("type")==="dynamic",c=n.getAttribute("availabilityStartTime"),h=c?new Date(c).getTime():void 0;let l;const f=n.getAttribute("mediaPresentationDuration"),p=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)l=zi(f);else if(p){const m=zi(p);r.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let b=0;const k=n.getAttribute("profiles")?.split(",")??[],w=k.includes(di.WEBM_AS_IN_FFMPEG)||k.includes(di.WEBM_AS_IN_SPEC)?xt.WEBM:xt.MP4;for(const m of u){const E=m.getAttribute("mimeType"),$=m.getAttribute("codecs"),R=m.getAttribute("contentType")??E?.split("/")[0],_=m.getAttribute("profiles")?.split(",")??[],C=m.querySelectorAll("Representation"),I=m.querySelector("SegmentTemplate");if(R===fe.TEXT){for(const S of C){const L=S.getAttribute("id")||"",N=m.getAttribute("lang"),j=S.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(j,e).toString(),ne=L.includes("_auto");s[fe.TEXT].push({id:L,lang:N,isAuto:ne,kind:fe.TEXT,url:ie})}continue}for(const S of C){const L=S.getAttribute("mimeType")??E,N=S.getAttribute("codecs")??$??"",j=S.getAttribute("contentType")??L?.split("/")[0]??R,ie=m.getAttribute("profiles")?.split(",")??[],ne=parseInt(S.getAttribute("width")??"",10),x=parseInt(S.getAttribute("height")??"",10),G=parseInt(S.getAttribute("bandwidth")??"",10)/1e3,K=S.getAttribute("frameRate")??"",oe=S.getAttribute("quality")??void 0,pe=K?mi(K):void 0,Oe=S.getAttribute("id")??(b++).toString(10),_t=j==="video"?`${x}p`:j==="audio"?`${G}Kbps`:N,vt=`${Oe}@${_t}`,z=S.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(z,e).toString(),ye=[...k,..._,...ie];let de;const et=S.querySelector("SegmentBase"),se=S.querySelector("SegmentTemplate")??I;if(et){const ue=S.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[le,Ue]=ue.split("-").map($e=>parseInt($e,10)),Te={from:le,to:Ue},Ne=S.querySelector("SegmentBase")?.getAttribute("indexRange"),[ht,tt]=Ne?Ne.split("-").map($e=>parseInt($e,10)):[],_e=Ne?{from:ht,to:tt}:void 0;de={type:xe.BYTE_RANGE,url:ce,initRange:Te,indexRange:_e}}else if(se){const ue={representationId:S.getAttribute("id")??void 0,bandwidth:S.getAttribute("bandwidth")??void 0},le=parseInt(se.getAttribute("timescale")??"",10),Ue=se.getAttribute("initialization")??"",Te=se.getAttribute("media"),Ne=parseInt(se.getAttribute("startNumber")??"",10)??1,ht=At(Ue,ue);if(!Te)throw new ReferenceError("No media attribute in SegmentTemplate");const tt=se.querySelectorAll("SegmentTimeline S")??[],_e=[];let $e=0,ft="",Ae=0;if(tt.length){let we=Ne,ae=0;for(const Be of tt){const ve=parseInt(Be.getAttribute("d")??"",10),He=parseInt(Be.getAttribute("r")??"",10)||0,it=parseInt(Be.getAttribute("t")??"",10);ae=Number.isFinite(it)?it:ae;const Bt=ve/le*1e3,Xt=ae/le*1e3;for(let Et=0;Et<He+1;Et++){const _s=At(Te,{...ue,segmentNumber:we.toString(10),segmentTime:(ae+Et*ve).toString(10)}),Ri=(Xt??0)+Et*Bt,Bs=Ri+Bt;we++,_e.push({time:{from:Ri,to:Bs},url:_s})}ae+=(He+1)*ve,$e+=(He+1)*Bt}Ae=ae/le*1e3,ft=At(Te,{...ue,segmentNumber:we.toString(10),segmentTime:ae.toString(10)})}else if(r.isNonNullable(l)){const ae=parseInt(se.getAttribute("duration")??"",10)/le*1e3,Be=Math.ceil(l/ae);let ve=0;for(let He=1;He<Be;He++){const it=At(Te,{...ue,segmentNumber:He.toString(10),segmentTime:ve.toString(10)});_e.push({time:{from:ve,to:ve+ae},url:it}),ve+=ae}Ae=ve,ft=At(Te,{...ue,segmentNumber:Be.toString(10),segmentTime:ve.toString(10)})}const pt={time:{from:Ae,to:1/0},url:ft};de={type:xe.TEMPLATE,baseUrl:ce,segmentTemplateUrl:Te,initUrl:ht,totalSegmentsDurationMs:$e,segments:_e,nextSegmentBeyondManifest:pt,timescale:le}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!L)continue;const ke={video:fe.VIDEO,audio:fe.AUDIO,text:fe.TEXT}[j];ke&&s[ke].push({id:vt,kind:ke,segmentReference:de,profiles:ye,duration:l,bitrate:G,mime:L,codecs:N,width:ne,height:x,fps:pe,quality:oe})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:w,representations:s}},gn=({id:a,width:e,height:t,bitrate:i,fps:s,quality:n})=>{const o=(n?It(n):void 0)??r.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:s}},bn=({id:a,bitrate:e})=>({id:a,bitrate:e}),Sn=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},yn=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),qi=a=>"size"in a,kt=a=>a.type===xe.TEMPLATE,Ai=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class Wi{onLastSegment$=new r.ValueSubject(!1);fullyBuffered$=new r.ValueSubject(!1);playingRepresentation$=new r.ValueSubject(void 0);playingRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;gaps=[];subscription=new r.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Re;destroyAbortController=new Re;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,s,{fetcher:n,tuning:o,getCurrentPosition:u,isActiveLowLatency:d,compatibilityMode:c=!1,manifest:h}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=c,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.isActiveLowLatency=d,this.isLive=!!h?.dynamic,this.container=i,i){case xt.MP4:this.containerParser=on;break;case xt.WEBM:this.containerParser=pn;break;default:r.assertNever(i)}this.initData=new Map(s.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=r.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);r.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 Rr(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),n=this.parsedInitData.get(t.id);r.assertNonNullable(i,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=r.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);r.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(r.isNullable(s)||r.isNullable(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),r.assertNonNullable(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const n=this.getCurrentPosition();r.isNonNullable(n)&&(this.isLive||(i.forEach(o=>o.status=M.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 Re,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Ee(this.sourceBuffer.buffered,e),l=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){const c=Ee(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(u.includes(s))c="high";else{const h=u.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===M.FED&&!u.length&&Ee(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=i.at(-1);d&&d.status===M.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;const s=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+s}),i=n.time.to;r.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,s=[];let n=0,o=t.length-1;do s.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()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.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=r.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const u of this.representations.keys()){const d=e.find(l=>l.id===u);d&&this.representations.set(u,d);const c=this.representations.get(u);if(!c||!kt(c.segmentReference))return;const h=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);r.assertNonNullable(i);const s=this.segments.get(t);r.assertNonNullable(s,"No segments for starting representation");const n=this.initData.get(t);if(r.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(s,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||!kt(t.segmentReference))return;const i=t.segmentReference.segments.map(u=>({...u,status:M.NONE,size:void 0})),s=this.segments.get(t.id)??[],n=s.at(-1)?.time.to??0,o=i?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const u=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,u)}else{const u=i.slice(o+1);this.segments.set(t.id,[...s,...u])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!kt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=At(i.segmentTemplateUrl,{segmentTime:s}),o=this.segments.get(t.id)??[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:M.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(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:l,time:{from:f,to:p}},g)=>{const y=f<=i&&p>=i,b=f>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&f<=i+k||p<=i+k;return(l===M.NONE||l===M.PARTIALLY_EJECTED&&b&&w&&this.sourceBuffer&&!Ct(this.sourceBuffer.buffered,i))&&b&&w});if(s===-1)return[];if(t!==xe.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<n.length&&(o<=c||u<=h);l++){const f=n[l];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===M.NONE||f.status===M.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type===xe.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=M.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:n,url:o,signal:u,onProgress:d,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await r.abortable(u,async function*(){const h=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(o,{range:n,signal:u,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const l=new DataView(h);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(l,f)}d&&s.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,u),s.segment.status=M.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!Ai(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const d of e)d.status=M.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:n,signal:o,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await r.abortable(o,async function*(){const d=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:s,onProgress:u,signal:o,priority:i}),this.failedDownloads=0}catch(d){if(!Ai(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}}prepareByteRangeFetchSegmentParams(e,t){if(kt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:s,signal:n,onProgress:(d,c)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:c,signal:n,onSegmentAppendFailed:o,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!kt(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 s=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},u=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,l)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:h,loaded:l,signal:n,onSegmentAppendFailed:o,representationId:t.id});u.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:s,signal:n,onProgress:c,onProgressTasks:u}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(i)&&(t=Ee(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const u of this.activeSegments){const{segment:d}=u;if(u.representationId===t){if(n.aborted){s();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){const c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(c);h?.byteLength&&(d.status=M.PARTIALLY_FED,u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:l}=h,f=d===xe.BYTE_RANGE,p=f?l.byte.to-l.byte.from+1:c;if(h.representationId!==t||!(!f||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const y=f?l.byte.from-i:0,b=f?l.byte.to-i:e.byteLength,k=y<s,w=b<=s;if(l.status===M.DOWNLOADING&&k&&w){l.status=M.DOWNLOADED;const m=new DataView(e.buffer,e.byteOffset+y,p);this.sourceBufferTaskQueue.append(m,n).then(E=>E&&!n.aborted?this.onSegmentFullyAppended(h,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&k&&(h.loadedBytes=Math.min(p,s-y),h.loadedBytes>h.feedingBytes)){const m=new DataView(e.buffer,e.byteOffset+y+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===p?m:this.containerParser.parseFeedableSegmentChunk(m);E?.byteLength&&(l.status=M.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then($=>{if(n.aborted)o();else if($)h.fedBytes+=E.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.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=M.FED,qi(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===M.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=M.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===M.PARTIALLY_FED||e.status===M.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=M.NONE),e.status=M.PARTIALLY_EJECTED):e.status=M.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=oi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async u=>{if(!u)return;const{init:d,dataView:c,segments:h}=u,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l);let f=h;this.isLive&&kt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const h=qi(c)?c.size??0:c.byte.to-c.byte.from;s+=h};for(const c of this.segments.values())for(const h of c){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===M.FED&&d(h)}if(u=isFinite(n)&&isFinite(o),!u){s=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const h of c){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===M.FED&&d(h)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const h=this.sourceBuffer.buffered.start(c)*1e3,l=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===M.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(l)){n=h,o=l;break}}if(u=isFinite(n)&&isFinite(o),!u&&i){s=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+c&&l.status===M.FED&&d(l)}return u=isFinite(n)&&isFinite(o),u?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 s={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,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){s=void 0;break}u>i.time.from&&u<i.time.to&&(s.from=u),o<i.time.to&&o>i.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=oi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:n})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:n}=s;if(n!==M.FED&&n!==M.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),u=Math.ceil(s.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=u),c=e.filter(h=>o>=h.from-t&&o<=h.to+t||u>=h.from-t&&u<=h.to+t);d||(c.length===1?s.status=M.PARTIALLY_EJECTED:s.status=M.NONE)}}}var Pt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(Pt||(Pt={}));class Tn{throughputEstimator;requestQuic;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);abortAllController=new Re;subscription=new r.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}=Li(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=r.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ct(t));const i=yield yt(t,{signal:this.abortAllController.signal}).catch(Ft);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=r.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:i,onProgress:s,priority:n="auto",signal:o,measureThroughput:u=!0,isLowLatency:d=!1}={}){let c=e;const h=new Headers;if(i)switch(t){case Pt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Pt.PARAM:{const C=new URL(c,location.href);C.searchParams.append("bytes",`${i.from}-${i.to}`),c=C.toString();break}default:r.assertNever(t)}this.requestQuic&&(c=ct(c));let l=this.abortAllController.signal,f;if(o){const C=new Re;if(f=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(o,"abort")).subscribe(()=>{try{C.abort()}catch(I){Ft(I)}}),this.abortAllController.signal.aborted||o.aborted)try{C.abort()}catch(I){Ft(I)}l=C.signal}const p=r.now(),g=yield yt(c,{priority:n,headers:h,signal:l}).catch(Ft),y=r.now();if(!g)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-p),!g.ok||!g.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!s&&!u)return f?.unsubscribe(),g.arrayBuffer();const[b,k]=g.body.tee(),w=b.getReader();u&&this.throughputEstimator?.trackStream(k,d);let m=0,E=new Uint8Array(0),$=!1;const R=C=>{f?.unsubscribe(),$=!0,Ft(C)},_=r.abortable(l,async function*({done:C,value:I}){if(m===0&&this.lastRequestFirstBytes$.next(r.now()-p),l.aborted){f?.unsubscribe();return}if(!C&&I){const S=new Uint8Array(E.length+I.length);S.set(E),S.set(I,E.length),E=S,m+=I.byteLength,s?.(new DataView(E.buffer),m),yield w?.read().then(_,R)}}.bind(this));return yield w?.read().then(_,R),f?.unsubscribe(),$?null:E.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case xe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case xe.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:r.assertNever(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==xe.BYTE_RANGE)return null;const{from:s,to:n}=e.initRange;let o=s,u=n,d=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,s),u=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:u},priority:i,measureThroughput:!1});if(!l)return null;const f=new DataView(l,s-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),g=e.indexRange??t.getIndexRange(p);if(!g)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,g.from-o,g.to-g.from+1);else{const k=yield this.fetch(e.url,{range:g,priority:i,measureThroughput:!1});if(!k)return null;y=new DataView(k)}const b=t.parseSegments(y,p,g);return{init:p,dataView:new DataView(l),segments:b}}.bind(this));fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==xe.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(o=>({...o,status:M.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const Ft=a=>{if(!Ai(a))throw a},wi=1e3,fi=(a,e,t)=>t*e+(1-t)*a,Cs=(a,e)=>a.reduce((t,i)=>t+i,0)/e,vn=(a,e,t,i)=>{let s=0,n=t;const o=Cs(a,e),u=e<i?e:i;for(let d=0;d<u;d++)a[n]>o?s++:s--,n=(a.length+n-1)%a.length;return Math.abs(s)===u};class xi{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 r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${t}`),this.smoothedSeries$=new Ge(`smoothed_${t}`),this.reportedSeries$=new Ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;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)&&(r.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 En extends xi{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=fi(this.slow,e,this.params.emaAlphaSlow),this.fast=fi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class kn extends xi{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Cs(this.pastMeasures,this.takenMeasures);this.emaSmoothed=fi(this.emaSmoothed,e,this.params.emaAlpha);const i=vn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class $n extends xi{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?fi(this.smoothed,e,this.params.emaAlpha):e}}class Pi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new En({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new kn({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 $n({initial:e,label:"liveEdgeDelay",...t})}}const An=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Qi=["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 wn=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new r.Subscription;representationSubscription=new r.Subscription;fetcher;state$=new q(Ce.NONE);currentVideoRepresentation$=new r.ValueSubject(void 0);currentVideoRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);isLive$=new r.ValueSubject(!1);liveDuration$=new r.ValueSubject(0);liveAvailabilityStartTime$=new r.ValueSubject(void 0);bufferLength$=new r.ValueSubject(0);liveLoadBufferLength$=new r.ValueSubject(0);livePositionFromPlayer$=new r.ValueSubject(0);liveEstimatedDelay;liveWaitingEventCallback;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new r.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Re;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Tn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Pi.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.liveWaitingEventCallback=Ys.debounce(this._liveWaitingEventCallback,this.tuning.dashCmafLive.maxWaitingDuration)}initManifest=r.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=be(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:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=r.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=mn(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||s===fe.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(([s,n])=>[s,n.filter(i)]))}}.bind(this));async seekLive(e){r.assertNonNullable(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.liveLastSeekOffset=e,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=be(this.manifestUrlString,e,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=r.abortable(this.destroyController.signal,async function*(e,t){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ce.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const i={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 Wi(fe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(t)&&(this.audioBufferManager=new Wi(fe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(r.interval(wi).subscribe(o=>{if(this.element?.paused){const u=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=be(this.manifestUrlString,u+wi,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Qi.map(o=>r.fromEvent(this.element,o))).pipe(r.map(o=>this.element?Ee(this.element.buffered,this.element.currentTime*1e3):0),r.filterChanged(),r.filter(o=>!!o)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(r.filter(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,l=u-d;let f=1+Math.sign(l)*h;Math.abs(l)<c?f=1:Math.abs(l)>c*2&&(f=1+Math.sign(l)*h*2),An(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{let d=0;if(u){const c=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-c}d&&this.liveLoadBufferLength$.getValue()!==d&&this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(r.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(r.assertNonNullable(this.element),this.liveWaitingEventCallback.cancel(),this.isUpdatingLive)return;const c=this.element.playbackRate,h=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P),l=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(l,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*c),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*c,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,y=this.isActiveLowLatency?d:u;let b=Ye.None;if(this.isActiveLowLatency?b=Ye.ActiveLowLatency:y<f+g&&y>=f?b=Ye.LiveWithTargetOffset:h!==0&&y<f&&(b=Ye.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),b===Ye.LiveForwardBuffering||b===Ye.LiveWithTargetOffset){const k=o-(f+p),w=Math.trunc(h+k/c);let m;u?w>0?m=w:m=0:m=h,this.manifestUrlString=be(this.manifestUrlString,m,X.DASH_CMAF_OFFSET_P)}b!==Ye.None&&b!==Ye.ActiveLowLatency&&(o=0,this.updateLive())}))}const s=r.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=r.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:s,someBufferEnded:n}).pipe(r.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(o=>!o.updating))try{this.source?.endOfStream()}catch(o){this.error$.next({id:"EndOfStream",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(r.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.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(){r.assertNonNullable(this.element),this.state$.setState(Ce.RUNNING),this.subscription.add(r.merge(...Qi.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.isLive$.getValue()&&this.liveWaitingEventCallback()})),this.tick()}async switchRepresentation(e,t){return{[fe.VIDEO]:this.videoBufferManager,[fe.AUDIO]:this.audioBufferManager,[fe.TEXT]:null}[e]?.switchTo(t)}seek(e,t){r.assertNonNullable(this.element),r.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),Ct(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(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}async _liveWaitingEventCallback(){try{await this.seekLive(this.liveLastSeekOffset)}catch(e){this.error$.next({id:"LiveWaitingEventCallback",category:r.ErrorCategory.WTF,message:"Error in seeking live in live waiting event callback",thrown:e})}}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=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class Ls{scene3D;subscription=new r.Subscription;videoState=new q(ee.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(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(Se(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new wn({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=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,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(r.map(c=>c.map(({track:h})=>h)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Ce.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=bn(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=gn(b);if(k){h.push({track:k,representation:b});const w=!this.params.tuning.isAudioDisabled&&Sn(f,p,b);w&&this.audioRepresentations.set(b.id,w)}}this.videoTracks$.next(h);for(const b of g){const k=yn(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.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 y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===Ce.REPRESENTATIOS_READY&&(this.videoState.setState(ee.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==Ce.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(fe.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(fe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=Ee(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==ee.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();return;case ee.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ee.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.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 r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(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(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ee.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:r.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),Xe(this.video)}}class Pn extends Ls{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)}}let Dn=class extends $s{constructor(e){super(e),this.liveOffset=new Wt}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(r.combine({interval:r.interval(ki),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===Z.PLAYING){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===Z.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,s)})}};class Cn extends Ls{constructor(e){super(e),this.liveOffset=new Wt}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(r.combine({interval:r.interval(wi),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ee.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===ee.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,s)})}}const je={};var Y;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));const Ot=(a,e)=>new r.Observable(t=>{const i=(s,n)=>t.next(n);return a.on(e,i),()=>a.off(e,i)});class Ln{subscription=new r.Subscription;videoState=new q(Y.INITIALIZING);video;params;hls;textTracksManager=new Fe;trackLevels=new Map;constructor(e){this.video=Je(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(Se(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),Xe(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(je.Hls=s.default,je.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){r.assertNonNullable(je.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},s=Ke(this.video),n=(c,h)=>this.subscription.add(c.subscribe(h,i));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(dt(this.video,e.isLooped,i)),this.subscription.add(Qe(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(rt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(Ot(this.hls,je.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),n(Ot(this.hls,je.Events.MANIFEST_PARSED).pipe(r.map(({levels:c})=>c.reduce((h,l)=>{const f=l.name||l.height.toString(10),{width:p,height:g}=l,y=It(l.attrs.QUALITY??"")??r.videoSizeToQuality({width:p,height:g});if(!y)return h;const b=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,k={id:f.toString(),quality:y,bitrate:l.bitrate/1e3,size:{width:p,height:g},fps:b};return this.trackLevels.set(f,{track:k,level:l}),h.push(k),h},[]))),t.availableVideoTracks$),n(Ot(this.hls,je.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){const h=[];for(const l of c.subtitleTracks){const f=l.name,p=l.attrs.URI||"",g=l.lang,y="internal";h.push({id:f,url:p,language:g,type:y})}e.internalTextTracks.startTransitionTo(h)}}),n(Ot(this.hls,je.Events.LEVEL_LOADING).pipe(r.map(({url:c})=>Se(c))),t.hostname$),this.subscription.add(Ve(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));const o=c=>Array.from(this.trackLevels.values()).find(({level:h})=>h===c)?.track,u=Ot(this.hls,je.Events.LEVEL_SWITCHED).pipe(r.map(({level:c})=>o(this.hls.levels[c])));u.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ve(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),c=>{if(r.isNullable(c))return;const h=this.trackLevels.get(c.id)?.level;if(!h)return;const l=this.hls.levels.indexOf(h),f=this.hls.currentLevel,p=this.hls.levels[f];!p||h.bitrate>p.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:u,onError:i})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==Y.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&s.state===V.Requested&&this.seek(s.position),t){case exports.PlaybackState.STOPPED:switch(e){case Y.STOPPED:break;case Y.READY:case Y.PLAYING:case Y.PAUSED:this.stop();break;default:r.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PLAYING:case Y.PAUSED:break;default:r.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Y.PLAYING:break;case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PAUSED:this.playIfAllowed();break;default:r.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Y.PAUSED:break;case Y.STOPPED:this.prepare();break;case Y.READY:this.videoState.setState(Y.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Y.PLAYING:this.pause();break;default:r.assertNever(e)}break;default:r.assertNever(t)}};prepare(){this.videoState.startTransitionTo(Y.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Y.PLAYING),await nt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(Y.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Y.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(Y.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Ji="X-Playback-Duration";var Xi=async a=>{const e=await yt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Ji)?parseInt(e.headers.get(Ji),10):void 0};const xn=a=>{let e=null;if(a.QUALITY&&(e=It(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=r.videoSizeToQuality({width:t,height:i})}return e??null},xs=async(a,e=a)=>{const s=(await(await yt(a)).text()).split(`
46
- `),n=[],o=[];for(let u=0;u<s.length;u++){const d=s[u],c=d.match(/^#EXT-X-STREAM-INF:(.+)/),h=d.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const l=Object.fromEntries(c[1].split(",").map(w=>w.split("="))),f=l.QUALITY??`stream-${l.BANDWIDTH}`,p=xn(l);let g;l.BANDWIDTH&&(g=parseInt(l.BANDWIDTH,10)/1e3||void 0),!g&&l["AVERAGE-BANDWIDTH"]&&(g=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const y=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let b;if(l.RESOLUTION){const[w,m]=l.RESOLUTION.split("x").map(E=>parseInt(E,10));w&&m&&(b={width:w,height:m})}const k=new URL(s[++u],e).toString();p&&n.push({id:f,quality:p,url:k,bandwidth:g,size:b,fps:y})}if(h){const l=Object.fromEntries(h[1].split(",").map(y=>y.split("=")).map(([y,b])=>[y,b.replace(/^"|"$/g,"")])),f=l.URI?.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,g=l.NAME;f&&p&&o.push({type:"internal",id:p,label:g,language:p,url:f,isAuto:!1})}}}return{qualityManifests:n,textTracks:o}};var W;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(W||(W={}));class Rn{subscription=new r.Subscription;videoState=new q(W.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);maxSeekBackTime$;liveOffset=new Wt;manifestStartTime$=new r.ValueSubject(void 0);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},xs(be(this.params.source.url),this.params.source.url).then(({qualityManifests:t})=>{this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.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(Se(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,i));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Se(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),u&&u.state===V.Requested&&this.seek(u.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:u,currentTime:d})=>this.params.output.liveTime$.next(u+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URLSearchParams(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:u,min:d}=t?.to??i??{};for(const[c,h]of[[u,"mq"],[d,"lq"]]){const l=String(parseFloat(c||""));h&&l&&s.set(h,l)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?X.DASH_CMAF_OFFSET_P:X.OFFSET_P,o=be(s.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),Xi(o).then(u=>{if(!r.isNullable(u))this.maxSeekBackTime$.next(u);else{const d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(r.isNullable(d)||!isFinite(d))try{yt(o).then(c=>c.text()).then(c=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){const l=new URL(h,o).toString();Xi(l).then(f=>{r.isNullable(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(W.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:r.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(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested){this.videoState.startTransitionTo(W.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case W.READY:i===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(W.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 h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else s?.to===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case W.CHANGING_MANIFEST:break;default:return r.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 In{subscription=new r.Subscription;videoState=new q(J.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(this.params.source.url).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:r.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(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d));if(n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Se(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===J.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===V.Requested&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!r.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:u}=this.video;this.subscription.add(r.merge(r.fromEvent(u,"addtrack"),r.fromEvent(u,"removetrack"),r.fromEvent(u,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<u.length;d++)u[d].mode="hidden"},i))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URLSearchParams(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:n,min:o}=t?.to??i??{};for(const[u,d]of[[n,"mq"],[o,"lq"]]){const c=String(parseFloat(u||""));d&&c&&s.set(d,c)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){nt(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:r.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(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=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 c=this.params.desiredState.seekState.getState();if(t===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(J.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:l}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:l*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested&&this.seek(c.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()):s?.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()):s?.to===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case J.CHANGING_MANIFEST:break;default:return r.assertNever(t)}}}var te;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(te||(te={}));class Nn{subscription=new r.Subscription;videoState=new q(te.STOPPED);video;trackUrls={};params;textTracksManager=new Fe;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const n=s.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=u=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,i));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&r.isNonNullable(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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),Xe(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;r.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];r.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ct(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(te.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:r.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!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.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(),u=this.params.desiredState.seekState.getState();if(n&&e!==te.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),u.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:d*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&&u.state===V.Requested&&this.seek(u.position),e){case te.READY:t===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(te.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case te.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(u=>!r.isInvariantQuality(u.track.quality)&&r.isLowerOrEqual(u.track.quality,e))?.track,n=this.params.desiredState.videoTrack.getState()?.id,o=this.trackUrls[n??"0"]?.track;if(s&&o&&r.isHigherOrEqual(o.quality,s.quality)&&(t=s),!t){const u=Object.values(this.trackUrls).filter(c=>!r.isInvariantQuality(c.track.quality)&&r.isHigher(c.track.quality,e)),d=u.length;d&&(t=u[d-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(n=>n.track);t=Tt(s,{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 Ki=["stun:videostun.mycdn.me:80"],_n=1e3,Bn=3,Ti=()=>null;class Mn{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ti;externalStopCallback=Ti;externalErrorCallback=Ti;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:Ki}]};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:r.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),_n)}normalizeOptions(e={}){const t={stunServerList:Ki,maxRetryNumber:Bn,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Q;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Q||(Q={}));class Vn{subscription;params;log;video;videoState=new q(Q.STOPPED);liveStreamClient;maxSeekBackTime$=new r.ValueSubject(0);constructor(e){this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Je(e.container),this.liveStreamClient=new Mn(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),Xe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(o)}`})});const s=Ke(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Qe(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Q.READY:break;case Q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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(Se(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:r.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Q.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:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){nt(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:r.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!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.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(Q.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===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case Q.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 r.assertNever(e)}}}class Zi{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const Rs=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,pi=document.createElement("video"),Fn='video/mp4; codecs="avc1.42000a,mp4a.40.2"',On='video/mp4; codecs="hev1.1.6.L93.B0"',Is='video/webm; codecs="vp09.00.10.08"',Ns='video/webm; codecs="av01.0.00M.08"',Un='audio/mp4; codecs="mp4a.40.2"',Hn='audio/webm; codecs="opus"',Me={mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(pi.canPlayType?.("application/x-mpegurl")||pi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Pe={mp4:!!pi.canPlayType?.("video/mp4"),webm:!!pi.canPlayType?.("video/webm"),cmaf:!0},We={h264:!!window.MediaSource?.isTypeSupported?.(Fn),h265:!!window.MediaSource?.isTypeSupported?.(On),vp9:!!window.MediaSource?.isTypeSupported?.(Is),av1:!!window.MediaSource?.isTypeSupported?.(Ns),aac:!!window.MediaSource?.isTypeSupported?.(Un),opus:!!window.MediaSource?.isTypeSupported?.(Hn)},$t=(We.h264||We.h265)&&We.aac;var ut;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(ut||(ut={}));var at;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg"})(at||(at={}));let mt;const jn=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:Ns}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Is}})]);mt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{jn()}catch(a){console.error(a)}const qt=Me.hls&&Pe.mp4,Yn=()=>Object.keys(We).filter(a=>We[a]),Gn=(a,e=!1)=>a.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Me.mse&&Pe.mp4&&$t;case exports.VideoFormat.DASH_SEP:return Me.mse&&Pe.mp4&&$t;case exports.VideoFormat.DASH_WEBM:return Me.mse&&Pe.webm&&We.vp9&&We.opus;case exports.VideoFormat.DASH_WEBM_AV1:return Me.mse&&Pe.webm&&We.av1&&We.opus;case exports.VideoFormat.DASH_LIVE:return Me.mse&&Pe.mp4&&$t;case exports.VideoFormat.DASH_LIVE_CMAF:return Me.mse&&Pe.mp4&&$t&&Pe.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Me.mse&&Pe.mp4&&$t;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return qt||e&&Me.mse&&Pe.mp4&&$t;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return qt;case exports.VideoFormat.MPEG:return Pe.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&We.h264&&(Pe.mp4||Pe.webm);default:return r.assertNever(t)}}),Ut=a=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(a){case ut.VP9:return[e,t];case ut.AV1:return[t,e];case ut.NONE:return[];case ut.SMOOTH:return mt?mt[t].smooth?[t,e]:mt[e].smooth?[e,t]:[t,e]:[e,t];case ut.POWER_EFFICIENT:return mt?mt[t].powerEfficient?[t,e]:mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(a)}return[e,t]},zn=({webmCodec:a,androidPreferredFormat:e})=>{if(Rs)switch(e){case at.MPEG:return[exports.VideoFormat.MPEG,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case at.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case at.DASH:return[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return qt?[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},qn=({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],s=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...s],o=[...s,...i];let u;if(Rs)switch(a){case at.DASH:{u=n;break}case at.HLS:case at.MPEG:{u=o;break}}else qt?u=o:u=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...u]:[...u,exports.VideoFormat.WEB_RTC_LIVE]},es=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 Wn=a=>new r.Observable(e=>{const t=new r.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:c,to:h})=>`${c}-${h}`)),s=a.desiredPlaybackState$.stateChangeEnded$,n=a.providerChanged$.pipe(r.map(({type:c})=>c!==void 0)),o=new r.Subject;let u=0,d="unknown";return t.add(i.subscribe(c=>{u&&window.clearTimeout(u),d=c,u=window.setTimeout(()=>o.next(c),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(u),d="unknown",u=0})),t.add(n.subscribe(c=>{u&&(window.clearTimeout(u),u=0,c&&(u=window.setTimeout(()=>o.next(d),a.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});const Qn={cacheDuration:12e4},Jn={chunkDuration:5e3,maxParallelRequests:5};class Xn{current$=new r.ValueSubject({type:void 0});providerError$=new r.Subject;noAvailableProvidersError$=new r.Subject;providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};subscription=new r.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Gn([...qn(this.params.tuning),...zn(this.params.tuning)],this.params.tuning.useHlsJs).filter(u=>r.isNonNullable(e.sources[u])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let n=[];i?n=[i]:s.length?n=[...t.filter(u=>!s.includes(u)),...t.filter(u=>s.includes(u))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Zi(n);const o=[...es(!0),...es(!1)];this.chromecastFormatsIterator=new Zi(o.filter(u=>r.isNonNullable(e.sources[u]))),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(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}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(),s=i.state!==V.None;if(this.params.desiredState.seekState.setState({state:V.Requested,position:s?i.position:t,forcePrecise:s?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 me.SCREEN:return this.createScreenProvider(t);case me.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Ba({...o,source:u,config:Qn})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJs?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new Pn({...o,source:u}):new xr({...o,source:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJsCMAF?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new Cn({...o,source:u}):new Dn({...o,source:u})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),qt||!this.params.tuning.useHlsJs?new In({...o,source:u}):new Ln({...o,source:u})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Rn({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Nn({...o,source:u})}case exports.VideoFormat.DASH_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new xa({...o,source:u,config:{...Jn,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Vn({container:i,source:u,desiredState:s,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 r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:n}=this.params,o=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(u),new Ks({connection:u,meta:n,container:i,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?me.CHROMECAST:me.SCREEN}chooseFormat(e){switch(e){case me.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case me.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case me.SCREEN:return this.screenFormatsIterator.next();case me.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case me.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case me.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const n=new URL(s);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(([s,n])=>[s,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;return e.add(r.merge(this.providerOutput.error$,Wn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(s=>({id:`ProviderHangup:${s}`,category:r.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const n=this.current$.getValue().destination;if(n===me.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(me.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=s.category===r.ErrorCategory.NETWORK,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit;u&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n??me.SCREEN)}})),e}}const Kn=5e3,ts="one_video_throughput",is="one_video_rtt",Yt=window.navigator.connection,ss=()=>{const a=Yt?.downlink;if(r.isNonNullable(a)&&a!==10)return a*1e3},as=()=>{const a=Yt?.rtt;if(r.isNonNullable(a)&&a!==3e3)return a},rs=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Gt{throughput;rtt;subscription=new r.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Gt.load(ts)||(e.useBrowserEstimation?ss():void 0)||Kn,i=Gt.load(is)??(e.useBrowserEstimation?as():void 0)??0;if(this.throughput$=new r.ValueSubject(t),this.rtt$=new r.ValueSubject(i),this.rttAdjustedThroughput$=new r.ValueSubject(rs(t,i,e.rttPenaltyRequestSize)),this.throughput=Pi.getSmoothedValue(t,-1,e),this.rtt=Pi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const o=ss();o&&this.throughput.next(o);const u=as();r.isNonNullable(u)&&this.rtt.next(u)};Yt&&"onchange"in Yt&&this.subscription.add(r.fromEvent(Yt,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{r.safeStorage.set(ts,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{r.safeStorage.set(is,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:s,rtt:n})=>rs(s,n,e.rttPenaltyRequestSize)),r.filter(s=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const s=new r.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:s.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}s.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,u=r.now(),d=o-t,c=u-i;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,n=r.now(),o=0,u=r.now();const d=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},c=async({done:h,value:l})=>{if(h)!t&&this.addRawSpeed(s,r.now()-n,1),this.concurrentDownloads.delete(e);else if(l){if(t){if(r.now()-u<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=l.byteLength;else{const p=u-n;p&&this.addRawSpeed(o,p,1,t),o=l.byteLength,n=r.now()}u=r.now()}else s+=l.byteLength,o+=l.byteLength,o>=this.tuningConfig.streamMinSampleSize&&r.now()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,r.now()-u,this.concurrentDownloads.size),o=0,u=r.now());await i?.read().then(c,d)}};this.concurrentDownloads.add(e),i?.read().then(c,d)}addRawSpeed(e,t,i=1,s=!1){if(Gt.sanityCheck(e,t,s)){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 s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=r.safeStorage.get(e);if(r.isNonNullable(t))return parseInt(t,10)??void 0}}const ns={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},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,maxWaitingDuration: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:ut.VP9,androidPreferredFormat:at.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Zn=a=>({...r.fillWithDefault(a,ns),configName:[...a.configName??[],...ns.configName]});var os=({seekState:a,position$:e})=>r.merge(a.stateChangeEnded$.pipe(r.map(({to:t})=>t.state===V.None?void 0:(t.position??NaN)/1e3),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>a.getState().state===V.None))),eo=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return r.assertNonNullable(e,`Wrong container or containerId {${a.container}}`),e};const to=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(r.filter(s=>s.length>0),r.once()).subscribe(s=>{s.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class io{subscription=new r.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new r.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new q(exports.PlaybackState.STOPPED),seekState:new q({state:V.None}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject};experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:la};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Zn(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new zs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Gt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const n=Reflect.get(t,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(u){const d=o.map(l=>JSON.stringify(l,(f,p)=>{const g=typeof p;return["number","string","boolean"].includes(g)?p:p===null?null:`<${g}>`})),c=`Player.${String(i)}`,h=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:r.ErrorCategory.WTF,message:h,thrown:u}),u}}}})}initVideo(e){return this.config=e,this.domContainer=eo(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Xn({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.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(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:V.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.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(r.filter(i=>i.length>0),r.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){r.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 to(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 s=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.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(){r.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===V.None?void 0:t.position;return r.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:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===V.Requested?this.desiredState.seekState.setState({...o,state:V.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===V.Applying&&(this.desiredState.seekState.setState({state:V.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:u})=>u).sort((u,d)=>r.isInvariantQuality(u)?1:r.isInvariantQuality(d)?-1:r.isHigher(d,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const u={};for(const d of o)d.fps&&(u[d.quality]=d.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o?.quality),this.info.videoBitrate$.next(o?.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.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(r.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(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:u,isLowLatency:d})=>{const c=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(u)<c/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:u,duration:d})=>o&&(Math.abs(d)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.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(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.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(r.once(),r.map(o=>o??r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.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 r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let s=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return o&&!u}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(r.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 u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),c=this.chromecastInitializer.castState$.getValue();let h;c===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:d?o?h=exports.Surface.PIP:u?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE:h=exports.Surface.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Tt(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(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.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;r.assertNonNullable(this.providerContainer),r.assertNonNullable(e),da(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ca(t)),this.providerContainer.current$.subscribe(({type:t})=>Kt("provider",t)),e.duration$.subscribe(t=>Kt("duration",t)),e.availableVideoTracks$.pipe(r.filter(t=>!!t.length),r.once()).subscribe(t=>Kt("tracks",t)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),e.position$.subscribe(new Ge("position")),e.currentVideoTrack$.pipe(r.map(t=>t?.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),e.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Kt("codecs",Yn())}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(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(s)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;s&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const so=`@vkontakte/videoplayer-core@${us}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=io;exports.SDK_VERSION=so;exports.VERSION=us;
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 ks{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 s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new wr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ar(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"),s=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(s,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(Pr,this.gl.VERTEX_SHADER),i=this.createShader(Dr,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 s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/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,s=this.camera.fov.y/180/2,n=e-i,o=t-s,u=e+i,d=t-s,c=e+i,h=t+s,l=e-i,f=t+s;return[n,o,u,d,c,h,l,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}}let $s=class{scene3D;subscription=new r.Subscription;videoState=new q(Z.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(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(ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $r({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=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,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(r.map(c=>c.map(({track:h})=>h)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Ce.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=yr(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=Sr(b);if(k){h.push({track:k,representation:b});const A=!this.params.tuning.isAudioDisabled&&Tr(f,p,b);A&&this.audioRepresentations.set(b.id,A)}}this.videoTracks$.next(h);for(const b of g){const k=vr(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.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 y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===Ce.REPRESENTATIOS_READY&&(this.videoState.setState(Z.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==Ce.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(fe.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(fe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=ke(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Z.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.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(Z.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Z.STOPPED:this.videoState.startTransitionTo(Z.READY),this.prepare();return;case Z.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Z.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(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(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.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),Xe(this.video)}},Cr=class extends $s{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)}};var pe;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(pe||(pe={}));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 di;(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"})(di||(di={}));var Re;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Re||(Re={}));var M;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(M||(M={}));var xt;(function(a){a.MP4="mp4",a.WEBM="webm"})(xt||(xt={}));var li;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(li||(li={}));var ee;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ee||(ee={}));let ws=!1;try{ws=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Lr{bufferFull$=new r.Subject;error$=new r.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 s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;ws&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!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:r.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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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:r.assertNever(t)}}}class Ne{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}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 As extends Ne{}class xr extends Ne{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Rr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Ir extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Nr extends Ne{data;constructor(e){super(e),this.data=this.content}}class ot extends Ne{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _r extends ot{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const u=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class Br extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Mr extends Ne{parseChildrenBoxes(){return lt(this.content)}}var St;(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"})(St||(St={}));class Vr extends ot{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=St.MONOSCOPIC;break;case 1:this.stereoMode=St.TOP_BOTTOM;break;case 2:this.stereoMode=St.LEFT_RIGHT;break;case 3:this.stereoMode=St.STEREO_CUSTOM;break;case 4:this.stereoMode=St.RIGHT_LEFT;break}this.cursor+=1}}class Fr extends ot{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Or extends ot{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ur extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Hr extends ot{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class jr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Yr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Gr extends ot{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class zr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class qr extends ot{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Wr extends ot{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Qr extends ot{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Jr={ftyp:xr,moov:Rr,moof:Ir,mdat:Nr,sidx:_r,trak:Br,mdia:Ur,mfhd:Gr,tkhd:Hr,traf:zr,tfhd:qr,tfdt:Wr,trun:Qr,minf:jr,sv3d:Mr,st3d:Vr,prhd:Fr,proj:Yr,equi:Or,unknown:As};class Xr{createBox(e,t){const i=Jr[e];return i?new i(t):new As(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Si.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Si=new Xr;function jt(a,e){const t=new Uint8Array(a.buffer),i=e.split("").map(o=>o.charCodeAt(0));let s=a.byteOffset,n=[];for(;s<t.byteLength;){if(t[s]===i[n.length]?n.push(t[s]):n=[],n.length===4){const u=new DataView(a.buffer,s-7,4).getUint32(0);return s-7+u>a.buffer.byteLength?null:Si.createBox(e,new DataView(a.buffer,s-7))}s++}return null}function $i(a,e){const t=[];let i=a.byteOffset;for(;i<a.buffer.byteLength;){const s=jt(new DataView(a.buffer,i,a.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function lt(a){const e=[];let t=0;for(;t<a.byteLength;){const i=Si.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Kr=new TextDecoder("ascii"),Zr=a=>Kr.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",en=a=>{const e=Si.createFromView(a);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,u={status:M.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,u})},tn=a=>{const e=$i(a,"mdat"),t=$i(a,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],n=i.source.byteOffset,u=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(a.buffer,n,u)},sn=(a,e)=>{const t=$i(a,"traf"),i=t[t.length-1].children.find(d=>d.type==="tfhd"),s=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,c)=>d+c,0):o=i.defaultSampleDuration*n.sampleCount,(Number(s.baseMediaDecodeTime)+o)/e*1e3},an=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(jt(a,"sv3d")){e.is3dVideo=!0;const i=jt(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=jt(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=jt(a,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},rn={validateData:Zr,parseInit:an,getIndexRange:()=>{},parseSegments:en,parseFeedableSegmentChunk:tn,getSegmentEndTime:sn};var E;(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"})(E||(E={}));var D;(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"})(D||(D={}));const Gi={[E.EBML]:{type:D.Master},[E.EBMLVersion]:{type:D.UnsignedInteger},[E.EBMLReadVersion]:{type:D.UnsignedInteger},[E.EBMLMaxIDLength]:{type:D.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[E.DocType]:{type:D.String},[E.DocTypeVersion]:{type:D.UnsignedInteger},[E.DocTypeReadVersion]:{type:D.UnsignedInteger},[E.Void]:{type:D.Binary},[E.Segment]:{type:D.Master},[E.SeekHead]:{type:D.Master},[E.Seek]:{type:D.Master},[E.SeekID]:{type:D.Binary},[E.SeekPosition]:{type:D.UnsignedInteger},[E.Info]:{type:D.Master},[E.TimestampScale]:{type:D.UnsignedInteger},[E.Duration]:{type:D.Float},[E.Tracks]:{type:D.Master},[E.TrackEntry]:{type:D.Master},[E.Video]:{type:D.Master},[E.Projection]:{type:D.Master},[E.ProjectionType]:{type:D.UnsignedInteger},[E.ProjectionPrivate]:{type:D.Master},[E.Chapters]:{type:D.Master},[E.Cluster]:{type:D.Master},[E.Timestamp]:{type:D.UnsignedInteger},[E.SilentTracks]:{type:D.Master},[E.SilentTrackNumber]:{type:D.UnsignedInteger},[E.Position]:{type:D.UnsignedInteger},[E.PrevSize]:{type:D.UnsignedInteger},[E.SimpleBlock]:{type:D.Binary},[E.BlockGroup]:{type:D.Master},[E.EncryptedBlock]:{type:D.Binary},[E.Attachments]:{type:D.Master},[E.Tags]:{type:D.Master},[E.Cues]:{type:D.Master},[E.CuePoint]:{type:D.Master},[E.CueTime]:{type:D.UnsignedInteger},[E.CueTrackPositions]:{type:D.Master},[E.CueTrack]:{type:D.UnsignedInteger},[E.CueClusterPosition]:{type:D.UnsignedInteger},[E.CueRelativePosition]:{type:D.UnsignedInteger},[E.CueDuration]:{type:D.UnsignedInteger},[E.CueBlockNumber]:{type:D.UnsignedInteger},[E.CueCodecState]:{type:D.UnsignedInteger},[E.CueReference]:{type:D.Master},[E.CueRefTime]:{type:D.UnsignedInteger}},Ps=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=hi(a,t),s=i in Gi,n=s?Gi[i].type:D.Binary,o=a.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(a.buffer,a.byteOffset+t+1,u-1),c=o&255>>u,h=hi(d),l=c*2**((u-1)*8)+h,f=t+u;let p;return f+l>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,l),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+l,value:p,valueSize:l}},hi=(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},qe=(a,e)=>{switch(e){case D.SignedInteger:return a.getInt8(0);case D.UnsignedInteger:return hi(a);case D.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(a);case D.UTF8:return new TextDecoder("utf-8").decode(a);case D.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case D.Master:return a;case D.Binary:return a;default:r.assertNever(e)}},Rt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=Ps(i);if(!e(s))return;s.type===D.Master&&Rt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},nn=a=>{if(a.getUint32(0)!==E.EBML)return!1;let e,t,i;const s=Ps(a);return Rt(s.value,({tag:n,type:o,value:u})=>(n===E.EBMLReadVersion?e=qe(u,o):n===E.DocType?t=qe(u,o):n===E.DocTypeReadVersion&&(i=qe(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ds=[E.Info,E.SeekHead,E.Tracks,E.TrackEntry,E.Video,E.Projection,E.ProjectionType,E.ProjectionPrivate,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],on=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],un=a=>{let e,t,i,s,n=!1,o=!1,u=!1,d,c,h=!1;const l=0;return Rt(a,({tag:f,type:p,value:g,valueSize:y})=>{if(f===E.SeekID){const b=qe(g,p);c=hi(b)}else f!==E.SeekPosition&&(c=void 0);return f===E.Segment?(e=g.byteOffset,t=g.byteOffset+y):f===E.Info?n=!0:f===E.SeekHead?o=!0:f===E.TimestampScale?i=qe(g,p):f===E.Duration?s=qe(g,p):f===E.SeekPosition&&c===E.Cues?d=qe(g,p):f===E.Tracks?Rt(g,({tag:b,type:k,value:A})=>b===E.ProjectionType?(h=qe(A,k)===1,!1):!0):n&&o&&Ds.includes(f)&&(u=!0),!u}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(s,"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(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},cn=a=>{if(r.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},dn=(a,e)=>{let t=!1,i=!1;const s=u=>r.isNonNullable(u.time)&&r.isNonNullable(u.position),n=[];let o;return Rt(a,({tag:u,type:d,value:c})=>{switch(u){case E.Cues:t=!0;break;case E.CuePoint:o&&s(o)&&n.push(o),o={};break;case E.CueTime:o&&(o.time=qe(c,d));break;case E.CueTrackPositions:break;case E.CueClusterPosition:o&&(o.position=qe(c,d));break;default:t&&Ds.includes(u)&&(i=!0)}return!(t&&i)}),o&&s(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:h}=u,l=n[d+1];return{status:M.NONE,time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},ln=a=>{let e=0,t=!1;try{Rt(a,i=>i.tag===E.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):on.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},hn={validateData:nn,parseInit:un,getIndexRange:cn,parseSegments:dn,parseFeedableSegmentChunk:ln},zi=a=>{if(!a.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},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),s=i?.[1]==="-"?-1:1,n={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},wt=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(i)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>r.isNullable(n)?u:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},fn=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],u=o.children,d=n.getAttribute("type")==="dynamic",c=n.getAttribute("availabilityStartTime"),h=c?new Date(c).getTime():void 0;let l;const f=n.getAttribute("mediaPresentationDuration"),p=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)l=zi(f);else if(p){const m=zi(p);r.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let b=0;const k=n.getAttribute("profiles")?.split(",")??[],A=k.includes(di.WEBM_AS_IN_FFMPEG)||k.includes(di.WEBM_AS_IN_SPEC)?xt.WEBM:xt.MP4;for(const m of u){const T=m.getAttribute("mimeType"),$=m.getAttribute("codecs"),R=m.getAttribute("contentType")??T?.split("/")[0],_=m.getAttribute("profiles")?.split(",")??[],C=m.querySelectorAll("Representation"),I=m.querySelector("SegmentTemplate");if(R===pe.TEXT){for(const S of C){const L=S.getAttribute("id")||"",N=m.getAttribute("lang"),j=S.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(j,e).toString(),ne=L.includes("_auto");s[pe.TEXT].push({id:L,lang:N,isAuto:ne,kind:pe.TEXT,url:ie})}continue}for(const S of C){const L=S.getAttribute("mimeType")??T,N=S.getAttribute("codecs")??$??"",j=S.getAttribute("contentType")??L?.split("/")[0]??R,ie=m.getAttribute("profiles")?.split(",")??[],ne=parseInt(S.getAttribute("width")??"",10),x=parseInt(S.getAttribute("height")??"",10),G=parseInt(S.getAttribute("bandwidth")??"",10)/1e3,K=S.getAttribute("frameRate")??"",oe=S.getAttribute("quality")??void 0,me=K?mi(K):void 0,Oe=S.getAttribute("id")??(b++).toString(10),_t=j==="video"?`${x}p`:j==="audio"?`${G}Kbps`:N,vt=`${Oe}@${_t}`,z=S.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(z,e).toString(),Te=[...k,..._,...ie];let de;const et=S.querySelector("SegmentBase"),se=S.querySelector("SegmentTemplate")??I;if(et){const ue=S.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[le,Ue]=ue.split("-").map(we=>parseInt(we,10)),ve={from:le,to:Ue},_e=S.querySelector("SegmentBase")?.getAttribute("indexRange"),[ht,tt]=_e?_e.split("-").map(we=>parseInt(we,10)):[],Be=_e?{from:ht,to:tt}:void 0;de={type:Re.BYTE_RANGE,url:ce,initRange:ve,indexRange:Be}}else if(se){const ue={representationId:S.getAttribute("id")??void 0,bandwidth:S.getAttribute("bandwidth")??void 0},le=parseInt(se.getAttribute("timescale")??"",10),Ue=se.getAttribute("initialization")??"",ve=se.getAttribute("media"),_e=parseInt(se.getAttribute("startNumber")??"",10)??1,ht=wt(Ue,ue);if(!ve)throw new ReferenceError("No media attribute in SegmentTemplate");const tt=se.querySelectorAll("SegmentTimeline S")??[],Be=[];let we=0,ft="",Ae=0;if(tt.length){let Pe=_e,ae=0;for(const Me of tt){const Ee=parseInt(Me.getAttribute("d")??"",10),He=parseInt(Me.getAttribute("r")??"",10)||0,it=parseInt(Me.getAttribute("t")??"",10);ae=Number.isFinite(it)?it:ae;const Bt=Ee/le*1e3,Xt=ae/le*1e3;for(let Et=0;Et<He+1;Et++){const _s=wt(ve,{...ue,segmentNumber:Pe.toString(10),segmentTime:(ae+Et*Ee).toString(10)}),Ri=(Xt??0)+Et*Bt,Bs=Ri+Bt;Pe++,Be.push({time:{from:Ri,to:Bs},url:_s})}ae+=(He+1)*Ee,we+=(He+1)*Bt}Ae=ae/le*1e3,ft=wt(ve,{...ue,segmentNumber:Pe.toString(10),segmentTime:ae.toString(10)})}else if(r.isNonNullable(l)){const ae=parseInt(se.getAttribute("duration")??"",10)/le*1e3,Me=Math.ceil(l/ae);let Ee=0;for(let He=1;He<Me;He++){const it=wt(ve,{...ue,segmentNumber:He.toString(10),segmentTime:Ee.toString(10)});Be.push({time:{from:Ee,to:Ee+ae},url:it}),Ee+=ae}Ae=Ee,ft=wt(ve,{...ue,segmentNumber:Me.toString(10),segmentTime:Ee.toString(10)})}const pt={time:{from:Ae,to:1/0},url:ft};de={type:Re.TEMPLATE,baseUrl:ce,segmentTemplateUrl:ve,initUrl:ht,totalSegmentsDurationMs:we,segments:Be,nextSegmentBeyondManifest:pt,timescale:le}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!L)continue;const $e={video:pe.VIDEO,audio:pe.AUDIO,text:pe.TEXT}[j];$e&&s[$e].push({id:vt,kind:$e,segmentReference:de,profiles:Te,duration:l,bitrate:G,mime:L,codecs:N,width:ne,height:x,fps:me,quality:oe})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:A,representations:s}},pn=({id:a,width:e,height:t,bitrate:i,fps:s,quality:n})=>{const o=(n?It(n):void 0)??r.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:s}},mn=({id:a,bitrate:e})=>({id:a,bitrate:e}),gn=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},bn=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),qi=a=>"size"in a,kt=a=>a.type===Re.TEMPLATE,wi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class Wi{onLastSegment$=new r.ValueSubject(!1);fullyBuffered$=new r.ValueSubject(!1);playingRepresentation$=new r.ValueSubject(void 0);playingRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;gaps=[];subscription=new r.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Ie;destroyAbortController=new Ie;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,s,{fetcher:n,tuning:o,getCurrentPosition:u,isActiveLowLatency:d,compatibilityMode:c=!1,manifest:h}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=c,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.isActiveLowLatency=d,this.isLive=!!h?.dynamic,this.container=i,i){case xt.MP4:this.containerParser=rn;break;case xt.WEBM:this.containerParser=hn;break;default:r.assertNever(i)}this.initData=new Map(s.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=r.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);r.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 Lr(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),n=this.parsedInitData.get(t.id);r.assertNonNullable(i,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=r.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);r.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(r.isNullable(s)||r.isNullable(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),r.assertNonNullable(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const n=this.getCurrentPosition();r.isNonNullable(n)&&(this.isLive||(i.forEach(o=>o.status=M.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 Ie,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=ke(this.sourceBuffer.buffered,e),l=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){const c=ke(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(u.includes(s))c="high";else{const h=u.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===M.FED&&!u.length&&ke(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=i.at(-1);d&&d.status===M.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;const s=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+s}),i=n.time.to;r.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,s=[];let n=0,o=t.length-1;do s.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()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.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=r.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const u of this.representations.keys()){const d=e.find(l=>l.id===u);d&&this.representations.set(u,d);const c=this.representations.get(u);if(!c||!kt(c.segmentReference))return;const h=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);r.assertNonNullable(i);const s=this.segments.get(t);r.assertNonNullable(s,"No segments for starting representation");const n=this.initData.get(t);if(r.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(s,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||!kt(t.segmentReference))return;const i=t.segmentReference.segments.map(u=>({...u,status:M.NONE,size:void 0})),s=this.segments.get(t.id)??[],n=s.at(-1)?.time.to??0,o=i?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const u=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,u)}else{const u=i.slice(o+1);this.segments.set(t.id,[...s,...u])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!kt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=wt(i.segmentTemplateUrl,{segmentTime:s}),o=this.segments.get(t.id)??[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:M.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(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:l,time:{from:f,to:p}},g)=>{const y=f<=i&&p>=i,b=f>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&f<=i+k||p<=i+k;return(l===M.NONE||l===M.PARTIALLY_EJECTED&&b&&A&&this.sourceBuffer&&!Ct(this.sourceBuffer.buffered,i))&&b&&A});if(s===-1)return[];if(t!==Re.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<n.length&&(o<=c||u<=h);l++){const f=n[l];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===M.NONE||f.status===M.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type===Re.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=M.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:n,url:o,signal:u,onProgress:d,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await r.abortable(u,async function*(){const h=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(o,{range:n,signal:u,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const l=new DataView(h);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(l,f)}d&&s.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,u),s.segment.status=M.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!wi(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const d of e)d.status=M.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:n,signal:o,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await r.abortable(o,async function*(){const d=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:s,onProgress:u,signal:o,priority:i}),this.failedDownloads=0}catch(d){if(!wi(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}}prepareByteRangeFetchSegmentParams(e,t){if(kt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:s,signal:n,onProgress:(d,c)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:c,signal:n,onSegmentAppendFailed:o,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!kt(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 s=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},u=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,l)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:h,loaded:l,signal:n,onSegmentAppendFailed:o,representationId:t.id});u.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:s,signal:n,onProgress:c,onProgressTasks:u}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(i)&&(t=ke(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const u of this.activeSegments){const{segment:d}=u;if(u.representationId===t){if(n.aborted){s();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){const c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(c);h?.byteLength&&(d.status=M.PARTIALLY_FED,u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:l}=h,f=d===Re.BYTE_RANGE,p=f?l.byte.to-l.byte.from+1:c;if(h.representationId!==t||!(!f||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const y=f?l.byte.from-i:0,b=f?l.byte.to-i:e.byteLength,k=y<s,A=b<=s;if(l.status===M.DOWNLOADING&&k&&A){l.status=M.DOWNLOADED;const m=new DataView(e.buffer,e.byteOffset+y,p);this.sourceBufferTaskQueue.append(m,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(h,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&k&&(h.loadedBytes=Math.min(p,s-y),h.loadedBytes>h.feedingBytes)){const m=new DataView(e.buffer,e.byteOffset+y+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===p?m:this.containerParser.parseFeedableSegmentChunk(m);T?.byteLength&&(l.status=M.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then($=>{if(n.aborted)o();else if($)h.fedBytes+=T.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.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=M.FED,qi(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===M.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=M.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===M.PARTIALLY_FED||e.status===M.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=M.NONE),e.status=M.PARTIALLY_EJECTED):e.status=M.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=oi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async u=>{if(!u)return;const{init:d,dataView:c,segments:h}=u,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l);let f=h;this.isLive&&kt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const h=qi(c)?c.size??0:c.byte.to-c.byte.from;s+=h};for(const c of this.segments.values())for(const h of c){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===M.FED&&d(h)}if(u=isFinite(n)&&isFinite(o),!u){s=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const h of c){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===M.FED&&d(h)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const h=this.sourceBuffer.buffered.start(c)*1e3,l=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===M.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(l)){n=h,o=l;break}}if(u=isFinite(n)&&isFinite(o),!u&&i){s=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+c&&l.status===M.FED&&d(l)}return u=isFinite(n)&&isFinite(o),u?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 s={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,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){s=void 0;break}u>i.time.from&&u<i.time.to&&(s.from=u),o<i.time.to&&o>i.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=oi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:n})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:n}=s;if(n!==M.FED&&n!==M.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),u=Math.ceil(s.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=u),c=e.filter(h=>o>=h.from-t&&o<=h.to+t||u>=h.from-t&&u<=h.to+t);d||(c.length===1?s.status=M.PARTIALLY_EJECTED:s.status=M.NONE)}}}var Pt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(Pt||(Pt={}));class Sn{throughputEstimator;requestQuic;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);abortAllController=new Ie;subscription=new r.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}=Li(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=r.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ct(t));const i=yield yt(t,{signal:this.abortAllController.signal}).catch(Ft);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=r.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:i,onProgress:s,priority:n="auto",signal:o,measureThroughput:u=!0,isLowLatency:d=!1}={}){let c=e;const h=new Headers;if(i)switch(t){case Pt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Pt.PARAM:{const C=new URL(c,location.href);C.searchParams.append("bytes",`${i.from}-${i.to}`),c=C.toString();break}default:r.assertNever(t)}this.requestQuic&&(c=ct(c));let l=this.abortAllController.signal,f;if(o){const C=new Ie;if(f=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(o,"abort")).subscribe(()=>{try{C.abort()}catch(I){Ft(I)}}),this.abortAllController.signal.aborted||o.aborted)try{C.abort()}catch(I){Ft(I)}l=C.signal}const p=r.now(),g=yield yt(c,{priority:n,headers:h,signal:l}).catch(Ft),y=r.now();if(!g)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-p),!g.ok||!g.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!s&&!u)return f?.unsubscribe(),g.arrayBuffer();const[b,k]=g.body.tee(),A=b.getReader();u&&this.throughputEstimator?.trackStream(k,d);let m=0,T=new Uint8Array(0),$=!1;const R=C=>{f?.unsubscribe(),$=!0,Ft(C)},_=r.abortable(l,async function*({done:C,value:I}){if(m===0&&this.lastRequestFirstBytes$.next(r.now()-p),l.aborted){f?.unsubscribe();return}if(!C&&I){const S=new Uint8Array(T.length+I.length);S.set(T),S.set(I,T.length),T=S,m+=I.byteLength,s?.(new DataView(T.buffer),m),yield A?.read().then(_,R)}}.bind(this));return yield A?.read().then(_,R),f?.unsubscribe(),$?null:T.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Re.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Re.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:r.assertNever(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Re.BYTE_RANGE)return null;const{from:s,to:n}=e.initRange;let o=s,u=n,d=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,s),u=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:u},priority:i,measureThroughput:!1});if(!l)return null;const f=new DataView(l,s-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),g=e.indexRange??t.getIndexRange(p);if(!g)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,g.from-o,g.to-g.from+1);else{const k=yield this.fetch(e.url,{range:g,priority:i,measureThroughput:!1});if(!k)return null;y=new DataView(k)}const b=t.parseSegments(y,p,g);return{init:p,dataView:new DataView(l),segments:b}}.bind(this));fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==Re.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(o=>({...o,status:M.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const Ft=a=>{if(!wi(a))throw a},Ai=1e3,fi=(a,e,t)=>t*e+(1-t)*a,Cs=(a,e)=>a.reduce((t,i)=>t+i,0)/e,yn=(a,e,t,i)=>{let s=0,n=t;const o=Cs(a,e),u=e<i?e:i;for(let d=0;d<u;d++)a[n]>o?s++:s--,n=(a.length+n-1)%a.length;return Math.abs(s)===u};class xi{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 r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${t}`),this.smoothedSeries$=new Ge(`smoothed_${t}`),this.reportedSeries$=new Ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;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)&&(r.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 Tn extends xi{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=fi(this.slow,e,this.params.emaAlphaSlow),this.fast=fi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class vn extends xi{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Cs(this.pastMeasures,this.takenMeasures);this.emaSmoothed=fi(this.emaSmoothed,e,this.params.emaAlpha);const i=yn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class En extends xi{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?fi(this.smoothed,e,this.params.emaAlpha):e}}class Pi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new vn({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 En({initial:e,label:"liveEdgeDelay",...t})}}const kn=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Qi=["timeupdate","progress","play","seeked","stalled","waiting"];var Le;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Le||(Le={}));let $n=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new r.Subscription;representationSubscription=new r.Subscription;fetcher;state$=new q(Le.NONE);currentVideoRepresentation$=new r.ValueSubject(void 0);currentVideoRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);isLive$=new r.ValueSubject(!1);liveDuration$=new r.ValueSubject(0);liveAvailabilityStartTime$=new r.ValueSubject(void 0);bufferLength$=new r.ValueSubject(0);liveLoadBufferLength$=new r.ValueSubject(0);livePositionFromPlayer$=new r.ValueSubject(0);liveEstimatedDelay;waitingEventInterval;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new r.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Ie;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Pi.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=r.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Se(t,i,X.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=r.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=fn(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||s===pe.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(([s,n])=>[s,n.filter(i)]))}}.bind(this));async seekLive(e){r.assertNonNullable(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Se(this.manifestUrlString,t,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initRepresentations=r.abortable(this.destroyController.signal,async function*(e,t){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Le.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const i={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 Wi(pe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(t)&&(this.audioBufferManager=new Wi(pe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(r.interval(Ai).subscribe(o=>{if(this.element?.paused){const u=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=Se(this.manifestUrlString,u+Ai,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Qi.map(o=>r.fromEvent(this.element,o))).pipe(r.map(o=>this.element?ke(this.element.buffered,this.element.currentTime*1e3):0),r.filterChanged(),r.filter(o=>!!o),r.tap(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(r.filter(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,l=u-d;let f=1+Math.sign(l)*h;Math.abs(l)<c?f=1:Math.abs(l)>c*2&&(f=1+Math.sign(l)*h*2),kn(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{let d=0;if(u){const c=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-c}d&&this.liveLoadBufferLength$.getValue()!==d&&this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(r.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(r.assertNonNullable(this.element),this.isUpdatingLive)return;const c=this.element.playbackRate,h=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P),l=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(l,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*c),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*c,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,y=this.isActiveLowLatency?d:u;let b=Ye.None;if(this.isActiveLowLatency?b=Ye.ActiveLowLatency:y<f+g&&y>=f?b=Ye.LiveWithTargetOffset:h!==0&&y<f&&(b=Ye.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),b===Ye.LiveForwardBuffering||b===Ye.LiveWithTargetOffset){const k=o-(f+p),A=this.normolizeLiveOffset(Math.trunc(h+k/c)),m=Math.abs(A-h);let T;!u||m<=this.tuning.dashCmafLive.offsetCalculationError?T=h:A>0&&m>this.tuning.dashCmafLive.offsetCalculationError?T=A:T=0,this.manifestUrlString=Se(this.manifestUrlString,T,X.DASH_CMAF_OFFSET_P)}b!==Ye.None&&b!==Ye.ActiveLowLatency&&(o=0,this.updateLive())}))}const s=r.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=r.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:s,someBufferEnded:n}).pipe(r.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(o=>!o.updating))try{this.source?.endOfStream()}catch(o){this.error$.next({id:"EndOfStream",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(r.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){r.assertNonNullable(this.element),this.state$.setState(Le.RUNNING),this.subscription.add(r.merge(...Qi.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){return{[pe.VIDEO]:this.videoBufferManager,[pe.AUDIO]:this.audioBufferManager,[pe.TEXT]:null}[e]?.switchTo(t)}seek(e,t){r.assertNonNullable(this.element),r.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),Ct(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Le.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:r.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class Ls{scene3D;subscription=new r.Subscription;videoState=new q(ee.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(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(ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $n({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=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,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(r.map(c=>c.map(({track:h})=>h)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Le.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=mn(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=pn(b);if(k){h.push({track:k,representation:b});const A=!this.params.tuning.isAudioDisabled&&gn(f,p,b);A&&this.audioRepresentations.set(b.id,A)}}this.videoTracks$.next(h);for(const b of g){const k=bn(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.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 y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===Le.REPRESENTATIOS_READY&&(this.videoState.setState(ee.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==Le.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(pe.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(pe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=ke(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==ee.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();return;case ee.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ee.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(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(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.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),Xe(this.video)}}class wn extends Ls{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)}}let An=class extends $s{constructor(e){super(e),this.liveOffset=new Wt}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(r.combine({interval:r.interval(ki),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===Z.PLAYING){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===Z.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,s)})}};class Pn extends Ls{constructor(e){super(e),this.liveOffset=new Wt}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(r.combine({interval:r.interval(Ai),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ee.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===ee.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,s)})}}const je={};var Y;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));const Ot=(a,e)=>new r.Observable(t=>{const i=(s,n)=>t.next(n);return a.on(e,i),()=>a.off(e,i)});class Dn{subscription=new r.Subscription;videoState=new q(Y.INITIALIZING);video;params;hls;textTracksManager=new Fe;trackLevels=new Map;constructor(e){this.video=Je(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(ye(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),Xe(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(je.Hls=s.default,je.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){r.assertNonNullable(je.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},s=Ke(this.video),n=(c,h)=>this.subscription.add(c.subscribe(h,i));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(dt(this.video,e.isLooped,i)),this.subscription.add(Qe(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(rt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(Ot(this.hls,je.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),w(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),n(Ot(this.hls,je.Events.MANIFEST_PARSED).pipe(r.map(({levels:c})=>c.reduce((h,l)=>{const f=l.name||l.height.toString(10),{width:p,height:g}=l,y=It(l.attrs.QUALITY??"")??r.videoSizeToQuality({width:p,height:g});if(!y)return h;const b=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,k={id:f.toString(),quality:y,bitrate:l.bitrate/1e3,size:{width:p,height:g},fps:b};return this.trackLevels.set(f,{track:k,level:l}),h.push(k),h},[]))),t.availableVideoTracks$),n(Ot(this.hls,je.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){const h=[];for(const l of c.subtitleTracks){const f=l.name,p=l.attrs.URI||"",g=l.lang,y="internal";h.push({id:f,url:p,language:g,type:y})}e.internalTextTracks.startTransitionTo(h)}}),n(Ot(this.hls,je.Events.LEVEL_LOADING).pipe(r.map(({url:c})=>ye(c))),t.hostname$),this.subscription.add(Ve(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));const o=c=>Array.from(this.trackLevels.values()).find(({level:h})=>h===c)?.track,u=Ot(this.hls,je.Events.LEVEL_SWITCHED).pipe(r.map(({level:c})=>o(this.hls.levels[c])));u.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ve(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),c=>{if(r.isNullable(c))return;const h=this.trackLevels.get(c.id)?.level;if(!h)return;const l=this.hls.levels.indexOf(h),f=this.hls.currentLevel,p=this.hls.levels[f];!p||h.bitrate>p.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:u,onError:i})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==Y.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&s.state===V.Requested&&this.seek(s.position),t){case exports.PlaybackState.STOPPED:switch(e){case Y.STOPPED:break;case Y.READY:case Y.PLAYING:case Y.PAUSED:this.stop();break;default:r.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PLAYING:case Y.PAUSED:break;default:r.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Y.PLAYING:break;case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PAUSED:this.playIfAllowed();break;default:r.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Y.PAUSED:break;case Y.STOPPED:this.prepare();break;case Y.READY:this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Y.PLAYING:this.pause();break;default:r.assertNever(e)}break;default:r.assertNever(t)}};prepare(){this.videoState.startTransitionTo(Y.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Y.PLAYING),await nt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Y.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(Y.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Ji="X-Playback-Duration";var Xi=async a=>{const e=await yt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Ji)?parseInt(e.headers.get(Ji),10):void 0};const Cn=a=>{let e=null;if(a.QUALITY&&(e=It(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=r.videoSizeToQuality({width:t,height:i})}return e??null},xs=async(a,e=a)=>{const s=(await(await yt(a)).text()).split(`
46
+ `),n=[],o=[];for(let u=0;u<s.length;u++){const d=s[u],c=d.match(/^#EXT-X-STREAM-INF:(.+)/),h=d.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const l=Object.fromEntries(c[1].split(",").map(A=>A.split("="))),f=l.QUALITY??`stream-${l.BANDWIDTH}`,p=Cn(l);let g;l.BANDWIDTH&&(g=parseInt(l.BANDWIDTH,10)/1e3||void 0),!g&&l["AVERAGE-BANDWIDTH"]&&(g=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const y=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let b;if(l.RESOLUTION){const[A,m]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));A&&m&&(b={width:A,height:m})}const k=new URL(s[++u],e).toString();p&&n.push({id:f,quality:p,url:k,bandwidth:g,size:b,fps:y})}if(h){const l=Object.fromEntries(h[1].split(",").map(y=>y.split("=")).map(([y,b])=>[y,b.replace(/^"|"$/g,"")])),f=l.URI?.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,g=l.NAME;f&&p&&o.push({type:"internal",id:p,label:g,language:p,url:f,isAuto:!1})}}}return{qualityManifests:n,textTracks:o}};var W;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(W||(W={}));class Ln{subscription=new r.Subscription;videoState=new q(W.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);maxSeekBackTime$;liveOffset=new Wt;manifestStartTime$=new r.ValueSubject(void 0);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},xs(Se(this.params.source.url),this.params.source.url).then(({qualityManifests:t})=>{if(t.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:r.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.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(ye(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,i));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ye(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),u&&u.state===V.Requested&&this.seek(u.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:u,currentTime:d})=>this.params.output.liveTime$.next(u+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:u,min:d}=t?.to??i??{};for(const[c,h]of[[u,"mq"],[d,"lq"]]){const l=String(parseFloat(c||""));h&&c&&s.searchParams.set(h,l)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?X.DASH_CMAF_OFFSET_P:X.OFFSET_P,o=Se(s.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),Xi(o).then(u=>{if(!r.isNullable(u))this.maxSeekBackTime$.next(u);else{const d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(r.isNullable(d)||!isFinite(d))try{yt(o).then(c=>c.text()).then(c=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){const l=new URL(h,o).toString();Xi(l).then(f=>{r.isNullable(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.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(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested){this.videoState.startTransitionTo(W.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case W.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(W.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 h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else s?.to===exports.PlaybackState.PAUSED&&(w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case W.CHANGING_MANIFEST:break;default:return r.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 xn{subscription=new r.Subscription;videoState=new q(J.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.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(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(this.params.source.url).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:r.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(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d));if(n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ye(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===J.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===V.Requested&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!r.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:u}=this.video;this.subscription.add(r.merge(r.fromEvent(u,"addtrack"),r.fromEvent(u,"removetrack"),r.fromEvent(u,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<u.length;d++)u[d].mode="hidden"},i))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:n,min:o}=t?.to??i??{};for(const[u,d]of[[n,"mq"],[o,"lq"]]){const c=String(parseFloat(u||""));d&&u&&s.searchParams.set(d,c)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.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(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(J.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:l}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:l*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested&&this.seek(c.position),t){case J.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case J.CHANGING_MANIFEST:break;default:return r.assertNever(t)}}}var te;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(te||(te={}));class Rn{subscription=new r.Subscription;videoState=new q(te.STOPPED);video;trackUrls={};params;textTracksManager=new Fe;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const n=s.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=u=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,i));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&r.isNonNullable(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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),Xe(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;r.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];r.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ct(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ye(t))}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.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!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.autoVideoTrackLimits.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(n&&e!==te.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),u.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:d*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&&u.state===V.Requested&&this.seek(u.position),e){case te.READY:t===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case te.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(u=>!r.isInvariantQuality(u.track.quality)&&r.isLowerOrEqual(u.track.quality,e))?.track,n=this.params.desiredState.videoTrack.getState()?.id,o=this.trackUrls[n??"0"]?.track;if(s&&o&&r.isHigherOrEqual(o.quality,s.quality)&&(t=s),!t){const u=Object.values(this.trackUrls).filter(c=>!r.isInvariantQuality(c.track.quality)&&r.isHigher(c.track.quality,e)),d=u.length;d&&(t=u[d-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(n=>n.track);t=Tt(s,{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 Ki=["stun:videostun.mycdn.me:80"],In=1e3,Nn=3,Ti=()=>null;class _n{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ti;externalStopCallback=Ti;externalErrorCallback=Ti;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:Ki}]};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:r.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),In)}normalizeOptions(e={}){const t={stunServerList:Ki,maxRetryNumber:Nn,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Q;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Q||(Q={}));class Bn{subscription;params;log;video;videoState=new q(Q.STOPPED);liveStreamClient;maxSeekBackTime$=new r.ValueSubject(0);constructor(e){this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Je(e.container),this.liveStreamClient=new _n(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),Xe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(o)}`})});const s=Ke(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Qe(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Q.READY:break;case Q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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(ye(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:r.VideoQuality.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Q.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:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.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!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.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(Q.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case Q.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}}class Zi{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const Rs=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,pi=document.createElement("video"),Mn='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Vn='video/mp4; codecs="hev1.1.6.L93.B0"',Is='video/webm; codecs="vp09.00.10.08"',Ns='video/webm; codecs="av01.0.00M.08"',Fn='audio/mp4; codecs="mp4a.40.2"',On='audio/webm; codecs="opus"',he={mms:!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(pi.canPlayType?.("application/x-mpegurl")||pi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!pi.canPlayType?.("video/mp4"),webm:!!pi.canPlayType?.("video/webm"),cmaf:!0},We={h264:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Mn),h265:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Vn),vp9:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Is),av1:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Ns),aac:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Fn),opus:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(On)},$t=(We.h264||We.h265)&&We.aac;var ut;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(ut||(ut={}));var at;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg"})(at||(at={}));let mt;const Un=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:Ns}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Is}})]);mt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Un()}catch(a){console.error(a)}const qt=he.hls&&De.mp4,Hn=()=>Object.keys(We).filter(a=>We[a]),jn=(a,e=!1,t=!1)=>a.filter(i=>{switch(i){case exports.VideoFormat.DASH:return he.mse&&De.mp4&&$t;case exports.VideoFormat.DASH_SEP:return(he.mse||he.mms&&t)&&De.mp4&&$t;case exports.VideoFormat.DASH_WEBM:return(he.mse||he.mms&&t)&&De.webm&&We.vp9&&We.opus;case exports.VideoFormat.DASH_WEBM_AV1:return(he.mse||he.mms&&t)&&De.webm&&We.av1&&We.opus;case exports.VideoFormat.DASH_LIVE:return he.mse&&De.mp4&&$t;case exports.VideoFormat.DASH_LIVE_CMAF:return(he.mse||he.mms&&t)&&De.mp4&&$t&&De.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return(he.mse||he.mms&&t)&&De.mp4&&$t;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return qt||e&&he.mse&&De.mp4&&$t;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return qt;case exports.VideoFormat.MPEG:return De.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return he.webrtc&&he.ws&&We.h264&&(De.mp4||De.webm);default:return r.assertNever(i)}}),Ut=a=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(a){case ut.VP9:return[e,t];case ut.AV1:return[t,e];case ut.NONE:return[];case ut.SMOOTH:return mt?mt[t].smooth?[t,e]:mt[e].smooth?[e,t]:[t,e]:[e,t];case ut.POWER_EFFICIENT:return mt?mt[t].powerEfficient?[t,e]:mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(a)}return[e,t]},Yn=({webmCodec:a,androidPreferredFormat:e})=>{if(Rs)switch(e){case at.MPEG:return[exports.VideoFormat.MPEG,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case at.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case at.DASH:return[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return qt?[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Gn=({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],s=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...s],o=[...s,...i];let u;if(Rs)switch(a){case at.DASH:{u=n;break}case at.HLS:case at.MPEG:{u=o;break}}else qt?u=o:u=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...u]:[...u,exports.VideoFormat.WEB_RTC_LIVE]},es=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 zn=a=>new r.Observable(e=>{const t=new r.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:c,to:h})=>`${c}-${h}`)),s=a.desiredPlaybackState$.stateChangeEnded$,n=a.providerChanged$.pipe(r.map(({type:c})=>c!==void 0)),o=new r.Subject;let u=0,d="unknown";return t.add(i.subscribe(c=>{u&&window.clearTimeout(u),d=c,u=window.setTimeout(()=>o.next(c),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(u),d="unknown",u=0})),t.add(n.subscribe(c=>{u&&(window.clearTimeout(u),u=0,c&&(u=window.setTimeout(()=>o.next(d),a.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});const qn={cacheDuration:12e4},Wn={chunkDuration:5e3,maxParallelRequests:5};class Qn{current$=new r.ValueSubject({type:void 0});providerError$=new r.Subject;noAvailableProvidersError$=new r.Subject;providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};subscription=new r.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=jn([...Gn(this.params.tuning),...Yn(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>r.isNonNullable(e.sources[u])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let n=[];i?n=[i]:s.length?n=[...t.filter(u=>!s.includes(u)),...t.filter(u=>s.includes(u))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Zi(n),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(n);const o=[...es(!0),...es(!1)];this.chromecastFormatsIterator=new Zi(o.filter(u=>r.isNonNullable(e.sources[u]))),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(console.log("Choose provider "+t),r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}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(),s=i.state!==V.None;if(this.params.desiredState.seekState.setState({state:V.Requested,position:s?i.position:t,forcePrecise:s?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 ge.SCREEN:return this.createScreenProvider(t);case ge.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case exports.VideoFormat.DASH:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Na({...o,source:u,config:qn})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJs?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new wn({...o,source:u})):new Cr({...o,source:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJsCMAF?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new Pn({...o,source:u}):new An({...o,source:u})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),qt||!this.params.tuning.useHlsJs?new xn({...o,source:u}):new Dn({...o,source:u})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Ln({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Rn({...o,source:u})}case exports.VideoFormat.DASH_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Ca({...o,source:u,config:{...Wn,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Bn({container:i,source:u,desiredState:s,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 r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:n}=this.params,o=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(u),new Js({connection:u,meta:n,container:i,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ge.CHROMECAST:ge.SCREEN}chooseFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ge.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.next();case ge.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case ge.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ge.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const n=new URL(s);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(([s,n])=>[s,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;const s=r.now();return e.add(r.merge(this.providerOutput.error$,zn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(n=>({id:`ProviderHangup:${n}`,category:r.ErrorCategory.WTF,message:`A ${n} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const n=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(n)})),e.add(this.providerError$.subscribe(n=>{const o=this.current$.getValue().destination;if(o===ge.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ge.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const u=n.category===r.ErrorCategory.NETWORK,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit,h=d&&(u&&t||!c),l=n.id.includes("partial_metadata"),f=r.now()-s;h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l&&f<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():c?(i++,this.reinitProvider()):this.switchToNextProvider(o??ge.SCREEN)}})),e}}const Jn=5e3,ts="one_video_throughput",is="one_video_rtt",Yt=window.navigator.connection,ss=()=>{const a=Yt?.downlink;if(r.isNonNullable(a)&&a!==10)return a*1e3},as=()=>{const a=Yt?.rtt;if(r.isNonNullable(a)&&a!==3e3)return a},rs=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Gt{throughput;rtt;subscription=new r.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Gt.load(ts)||(e.useBrowserEstimation?ss():void 0)||Jn,i=Gt.load(is)??(e.useBrowserEstimation?as():void 0)??0;if(this.throughput$=new r.ValueSubject(t),this.rtt$=new r.ValueSubject(i),this.rttAdjustedThroughput$=new r.ValueSubject(rs(t,i,e.rttPenaltyRequestSize)),this.throughput=Pi.getSmoothedValue(t,-1,e),this.rtt=Pi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const o=ss();o&&this.throughput.next(o);const u=as();r.isNonNullable(u)&&this.rtt.next(u)};Yt&&"onchange"in Yt&&this.subscription.add(r.fromEvent(Yt,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{r.safeStorage.set(ts,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{r.safeStorage.set(is,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:s,rtt:n})=>rs(s,n,e.rttPenaltyRequestSize)),r.filter(s=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const s=new r.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:s.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}s.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,u=r.now(),d=o-t,c=u-i;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,n=r.now(),o=0,u=r.now();const d=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},c=async({done:h,value:l})=>{if(h)!t&&this.addRawSpeed(s,r.now()-n,1),this.concurrentDownloads.delete(e);else if(l){if(t){if(r.now()-u<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=l.byteLength;else{const p=u-n;p&&this.addRawSpeed(o,p,1,t),o=l.byteLength,n=r.now()}u=r.now()}else s+=l.byteLength,o+=l.byteLength,o>=this.tuningConfig.streamMinSampleSize&&r.now()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,r.now()-u,this.concurrentDownloads.size),o=0,u=r.now());await i?.read().then(c,d)}};this.concurrentDownloads.add(e),i?.read().then(c,d)}addRawSpeed(e,t,i=1,s=!1){if(Gt.sanityCheck(e,t,s)){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 s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=r.safeStorage.get(e);if(r.isNonNullable(t))return parseInt(t,10)??void 0}}const ns={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},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ut.VP9,androidPreferredFormat:at.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Xn=a=>({...r.fillWithDefault(a,ns),configName:[...a.configName??[],...ns.configName]});var os=({seekState:a,position$:e})=>r.merge(a.stateChangeEnded$.pipe(r.map(({to:t})=>t.state===V.None?void 0:(t.position??NaN)/1e3),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>a.getState().state===V.None))),Kn=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return r.assertNonNullable(e,`Wrong container or containerId {${a.container}}`),e};const Zn=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(r.filter(s=>s.length>0),r.once()).subscribe(s=>{s.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class eo{subscription=new r.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new r.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new q(exports.PlaybackState.STOPPED),seekState:new q({state:V.None}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject};experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:ca};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Xn(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ys({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Gt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const n=Reflect.get(t,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(u){const d=o.map(l=>JSON.stringify(l,(f,p)=>{const g=typeof p;return["number","string","boolean"].includes(g)?p:p===null?null:`<${g}>`})),c=`Player.${String(i)}`,h=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:r.ErrorCategory.WTF,message:h,thrown:u}),u}}}})}initVideo(e){return this.config=e,this.domContainer=Kn(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Qn({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.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(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:V.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.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(r.filter(i=>i.length>0),r.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){r.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 Zn(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 s=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.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(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===V.None?void 0:t.position;return r.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:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===V.Requested?this.desiredState.seekState.setState({...o,state:V.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===V.Applying&&(this.desiredState.seekState.setState({state:V.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:u})=>u).sort((u,d)=>r.isInvariantQuality(u)?1:r.isInvariantQuality(d)?-1:r.isHigher(d,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const u={};for(const d of o)d.fps&&(u[d.quality]=d.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o?.quality),this.info.videoBitrate$.next(o?.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.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(r.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(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:u,isLowLatency:d})=>{const c=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(u)<c/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:u,duration:d})=>o&&(Math.abs(d)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.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(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.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(r.once(),r.map(o=>o??r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.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 r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let s=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return o&&!u}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(r.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 u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),c=this.chromecastInitializer.castState$.getValue();let h;c===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:d?o?h=exports.Surface.PIP:u?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE:h=exports.Surface.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Tt(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(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.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;r.assertNonNullable(this.providerContainer),r.assertNonNullable(e),ua(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>oa(t)),this.providerContainer.current$.subscribe(({type:t})=>Kt("provider",t)),e.duration$.subscribe(t=>Kt("duration",t)),e.availableVideoTracks$.pipe(r.filter(t=>!!t.length),r.once()).subscribe(t=>Kt("tracks",t)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),e.position$.subscribe(new Ge("position")),e.currentVideoTrack$.pipe(r.map(t=>t?.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),e.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Kt("codecs",Hn())}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(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(s)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;s&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const to=`@vkontakte/videoplayer-core@${us}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=eo;exports.SDK_VERSION=to;exports.VERSION=us;