@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.esm.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
- import{ValueSubject as g,Subject as I,Subscription as se,isNonNullable as P,ErrorCategory as L,isNullable as Y,fromEvent as M,assertNever as N,merge as O,tap as _i,map as A,observableFrom as Oe,filterChanged as le,assertNonNullable as w,debounce as Qe,getHighestQuality as br,timeout as yr,getCurrentBrowser as Wi,CurrentClientBrowser as us,combine as xe,once as be,mapTo as ti,filter as K,now as ne,assertNotEmptyArray as Tr,videoSizeToQuality as Ct,isInvariantQuality as Yt,isHigher as ei,isLower as Ii,isHigherOrEqual as is,isLowerOrEqual as Ys,Observable as Qi,interval as Gt,VideoQuality as je,videoQualityToHeight as vr,abortable as oe,getExponentialDelay as bi,throttle as Er,isIOS as kr,CurrentClientDevice as $r,safeStorage as Zi,fillWithDefault as Ar,Logger as wr}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as Ed,Subject as kd,Subscription as $d,ValueSubject as Ad,VideoQuality as wd}from"@vkontakte/videoplayer-shared/esnext.esm.js";import Dr from"lodash/debounce.js";import{debounce as Pr}from"lodash";const xr="2.0.98-dev.27a468df.0";var f;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(f||(f={}));var y;(function(r){r.MPEG="MPEG",r.DASH="DASH",r.DASH_SEP="DASH_SEP",r.DASH_SEP_VK="DASH_SEP",r.DASH_WEBM="DASH_WEBM",r.DASH_WEBM_AV1="DASH_WEBM_AV1",r.DASH_WEBM_VK="DASH_WEBM",r.DASH_ONDEMAND="DASH_ONDEMAND",r.DASH_ONDEMAND_VK="DASH_ONDEMAND",r.DASH_LIVE="DASH_LIVE",r.DASH_LIVE_CMAF="DASH_LIVE_CMAF",r.DASH_LIVE_WEBM="DASH_LIVE_WEBM",r.HLS="HLS",r.HLS_ONDEMAND="HLS_ONDEMAND",r.HLS_JS="HLS",r.HLS_LIVE="HLS_LIVE",r.HLS_LIVE_CMAF="HLS_LIVE_CMAF",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var _e;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(_e||(_e={}));var Le;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(Le||(Le={}));var vi;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(vi||(vi={}));var j;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(j||(j={}));var Lt;(function(r){r.NONE="none",r.INLINE="inline",r.FULLSCREEN="fullscreen",r.SECOND_SCREEN="second_screen",r.PIP="pip"})(Lt||(Lt={}));var Lr=r=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Rr{connection$=new g(void 0);castState$=new g(Le.NOT_AVAILABLE);errorEvent$=new I;contentId;realCastState$=new g(Le.NOT_AVAILABLE);subscription=new se;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=P(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},s||Lr("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:L.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(){P(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Y(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Y(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(M(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 N(s.sessionState)}})).add(O(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_i(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),A(s=>s.castState)),Oe([i.getCastState()])).pipe(le(),A(Ir),_i(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const a=s===Le.CONNECTED,n=P(this.connection$.getValue());if(a&&!n){const o=i.getCurrentSession();w(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(Y(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===Le.CONNECTED?P(this.connection$.getValue())?Le.CONNECTED:Le.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:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Ir=r=>{switch(r){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Le.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Le.AVAILABLE;case cast.framework.CastState.CONNECTING:return Le.CONNECTING;case cast.framework.CastState.CONNECTED:return Le.CONNECTED;default:return N(r)}};var fe;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",r[r.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Me=(r,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{const i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:N(t)}return r};const Bi=(r,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:N(e)}};var R=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class de{state;prevState;transition;transitionStarted$=new I;transitionEnded$=new I;transitionUpdated$=new I;forceChanged$=new I;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(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||P(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 Cr=r=>{switch(r){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return N(r)}};var W;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(W||(W={}));const _r=5,Br=5,Mr=500,gs=7e3;class Or{subscription=new se;loadMediaTimeoutSubscription=new se;videoState=new de(W.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(Cr(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 se;this.subscription.add(e),this.subscription.add(O(this.videoState.stateChangeStarted$.pipe(A(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(A(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,a)=>this.subscription.add(s.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new I;e.add(s.pipe(Qe(Mr)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===j.Applying||Math.abs(o-a)>_r)&&s.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:a}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Br&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,f.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:N(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(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(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.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:j.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===W.PAUSED||e===W.PLAYING)&&(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===W.PLAYING||e===W.PAUSED)&&(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.params.desiredState.playbackState.getTransition()?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY)}handleRemoteStop(){this.videoState.getState()!==W.STOPPED&&this.videoState.setState(W.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,a;switch(e){case y.MPEG:{const d=t[e];w(d);const h=br(Object.keys(d));w(h);const u=d[h];w(u),i=u,s="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const d=t[e];w(d),i=d.url,s="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const d=t[e];w(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const d=t[e];w(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const d=t[e];w(d),i=Me(d.url),s="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.VIDEO_PIPELINE,message:d,thrown:h}),h}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return P(o)&&(n.metadata.title=o),P(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===j.Applying||i.state===j.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,a)=>{this.loadMediaTimeoutSubscription.add(yr(gs).subscribe(()=>a(`timeout(${gs})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.VIDEO_PIPELINE,message:a,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(),a=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(a)};`}),i===f.STOPPED){e!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.stop());return}if(!t){if(s?.to!==f.PAUSED&&a.state===j.Requested&&e!==W.STOPPED){this.seek(a.position/1e3);return}switch(i){case f.READY:{switch(e){case W.PLAYING:case W.PAUSED:case W.READY:break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PLAYING:{switch(e){case W.PLAYING:break;case W.PAUSED:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.READY:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case W.PLAYING:this.videoState.startTransitionTo(W.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case W.PAUSED:break;case W.READY:this.videoState.startTransitionTo(W.PAUSED),this.videoState.setState(W.PAUSED);break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}default:N(i)}}}}var Nr=r=>{let e,t=!1,i=!1;r.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),r.extend("MediaSourceController",function(){const{parent:s}=this,a=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&e?.()}}},!0)},Fr=r=>{const e=new g(1/0),t=new I,i=new g(void 0),s=new g(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const S=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;P(b)&&!isNaN(b)&&e.next(b)}const l=u["x-delivery-type"]??vi.HTTP1,p={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(l),s.next(p)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return r.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(l){if(l.request.type==="MPD"){const p=l.onload,S=l.progress;l.onload=function(...v){return c(this),p(...v)},l.progress=function(...v){return d(this),S(...v)},o()}return u(l)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},It=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Vr=r=>r.extend("RequestModifier",()=>({modifyRequestURL:It}),!0),Ur=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const nt=(r,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:a}={})=>{const n=r.getState(),o=e(),c=Y(s),d=new se;return s&&d.add(s.subscribe(h=>{const u=r.getState();i(h,u)&&r.setState(h)},a)),i(o,n)||(t(n),c&&r.setState(n)),d.add(r.stateChangeStarted$.subscribe(h=>{t(h.to),c&&r.setState(h.to)},a)),d},_t=(r,e,t)=>nt(e,()=>r.loop,i=>{P(i)&&(r.loop=i)},{onError:t}),St=(r,e,t,i)=>nt(e,()=>({muted:r.muted,volume:r.volume}),s=>{P(s)&&(r.muted=s.muted,r.volume=s.volume)},{equal:(s,a)=>s===a||s?.muted===a?.muted&&s?.volume===a?.volume,changed$:t,onError:i}),Dt=(r,e,t,i)=>nt(e,()=>r.playbackRate,s=>{P(s)&&(r.playbackRate=s)},{changed$:t,onError:i}),Hr=r=>["__",r.language,r.label].join("|"),Yr=(r,e)=>{if(r.id===e)return!0;const[t,i,s]=e.split("|");return r.language===i&&r.label===s};class ot{available$=new I;current$=new g(void 0);error$=new I;video;cueSettings;subscription=new se;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=a=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(nt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{P(a)&&this.setInternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(nt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{P(a)&&this.setExternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(nt(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:s})),this.subscription.add(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){w(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(O(M(e,"addtrack"),M(e,"removetrack"),Oe(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),le((i,s)=>i.length===s.length&&i.every(({id:a},n)=>a===s[n].id))).subscribe(this.available$)),this.subscription.add(O(M(e,"change"),Oe(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),A(i=>i&&this.htmlTextTrackToITextTrack(i).id),le()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(M(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=a=>{const n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(M(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;P(t.align)&&(s.align=t.align),P(t.position)&&(s.position=t.position),P(t.size)&&(s.size=t.size),P(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){w(this.video);const t=[...this.video.textTracks];return e?t:t.filter(ot.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Hr(e),a=this.externalTracks.has(s),n=s.includes("auto");return a?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,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:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){w(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Y(e)||!Yr(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){w(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){w(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 hs=r=>{r.removeAttribute("src"),r.load()},Gr=r=>{try{r.pause(),r.playbackRate=0,hs(r),r.remove()}catch(e){console.error(e)}};class zr{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 ss=window.WeakMap?new WeakMap:new zr,bt=r=>{let e=r.querySelector("video");const t=!!e;return e?hs(e):(e=document.createElement("video"),r.appendChild(e)),ss.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},yt=r=>{const e=ss.get(r);ss.delete(r),e?hs(r):Gr(r)};class $i{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 Gs=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ss=r=>{const e=Gs(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},qr=r=>{const e=Gs(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},rs=3;class Wr{_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 a=this._source.buffered.end(t);s>e&&s-e<rs&&(s=e),this._buffer.push({from:s,to:a,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||rs))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:a})=>{const n=s>=e&&s<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(s,e):s<e&&a>t?(i(t,a),i(s,e)):i(s,a))})}destroy(){this._buffer=[]}}var zs=(r,e,t=rs)=>{let i=0,s=0;for(let a=0;a<r.length;a++){const n=r.start(a),o=r.end(a);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=a-1;c>=0;c--)r.end(c)+t>=i&&(i=r.start(c));for(let c=a+1;c<r.length;c++)r.start(c)-t<=s&&(s=r.end(c))}}return{from:i,to:s}};const Tt=r=>{const e=m=>M(r,m).pipe(ti(void 0)),i=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>M(r,m))).pipe(A(m=>m.type==="ended"?r.readyState<2:r.readyState<3),le()),s=O(M(r,"progress"),M(r,"timeupdate")).pipe(A(()=>zs(r.buffered,r.currentTime))),n=Wi().browser===us.Safari?xe({play:e("play").pipe(be()),playing:e("playing")}).pipe(ti(void 0)):e("playing"),o=M(r,"volumechange").pipe(A(()=>({muted:r.muted,volume:r.volume}))),c=M(r,"ratechange").pipe(A(()=>r.playbackRate)),d=M(r,"error").pipe(K(()=>!!(r.error||r.played.length)),A(()=>{const m=r.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:r.error??void 0}})),h=M(r,"timeupdate").pipe(A(()=>r.currentTime)),u=new I,l=.3;let p;h.subscribe(m=>{r.loop&&P(p)&&P(m)&&p>=r.duration-l&&m<=l&&u.next(p),p=m});const S=M(r,"enterpictureinpicture"),v=M(r,"leavepictureinpicture"),b=new g(qr(r));S.subscribe(()=>b.next(!0)),v.subscribe(()=>b.next(!1));const D=new g(Ss(r));return M(r,"fullscreenchange").pipe(A(()=>Ss(r))).subscribe(D),{playing$:n,pause$:e("pause").pipe(K(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:M(r,"durationchange").pipe(A(()=>r.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:b,inFullscreen$:D}},ji=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let ls=!1,At={};const Qr=r=>{ls=r},jr=()=>{At={}},Jr=r=>{r(At)},Pi=(r,e)=>{ls&&(At.meta=At.meta??{},At.meta[r]=e)};class ft{name;constructor(e){this.name=e}next(e){if(!ls)return;At.series=At.series??{};const t=At.series[this.name]??[];t.push([Date.now(),e]),At.series[this.name]=t}}var Vt;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(Vt||(Vt={}));const Xr=new ft("best_bitrate"),Kr=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class qs{last;history={};recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Zr='Assertion "ABR Tracks is empty array" failed',qt=(r,{container:e,throughput:t,tuning:i,limits:s,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{Tr(r,Zr);const l=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*i.containerSizeFactor,height:e.height*l*i.containerSizeFactor},S=p&&Ct(p),v=i.considerPlaybackRate&&P(o)?o:1,b=r.filter(T=>!Yt(T.quality)).sort((T,V)=>ei(T.quality,V.quality)?-1:1),D=b.at(-1)?.quality,C=b.at(0)?.quality,m=Y(s)||P(s.min)&&P(s.max)&&Ii(s.max,s.min)||P(s.min)&&C&&ei(s.min,C)||P(s.max)&&D&&Ii(s.max,D),$=v*Kr(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},q=b.filter(T=>(S?Ii(T.quality,S):!0)?(P(t)&&isFinite(t)&&P(T.bitrate)?t-a>=T.bitrate*$:!0)?i.lazyQualitySwitch&&P(i.minBufferToSwitchUp)&&c&&!Yt(c.quality)&&(n??0)<i.minBufferToSwitchUp&&ei(T.quality,c.quality)?(x[T.quality]=Vt.Buffer,!1):!!h&&is(T.quality,h)?(x[T.quality]=Vt.DroppedFramesLimit,!1):m||(Y(s.max)||Ys(T.quality,s.max))&&(Y(s.min)||is(T.quality,s.min))?!0:(x[T.quality]=Vt.FitsQualityLimits,!1):(x[T.quality]=Vt.FitsThroughput,!1):(x[T.quality]=Vt.FitsContainer,!1))[0];q&&q.bitrate&&Xr.next(q.bitrate);const F=q??b[Math.ceil((b.length-1)/2)]??r[0];F.quality!==d?.last?.quality&&u({message:`
6
+ import{ValueSubject as m,Subject as I,Subscription as se,isNonNullable as P,ErrorCategory as x,isNullable as Y,fromEvent as M,assertNever as N,merge as O,tap as vi,map as A,observableFrom as Ne,filterChanged as le,assertNonNullable as D,debounce as je,getHighestQuality as br,timeout as yr,getCurrentBrowser as Wi,CurrentClientBrowser as us,combine as Le,once as be,mapTo as ti,filter as K,now as ne,assertNotEmptyArray as Tr,videoSizeToQuality as Ct,isInvariantQuality as Yt,isHigher as ei,isLower as Ci,isHigherOrEqual as is,isLowerOrEqual as Ys,Observable as Qi,debounceFn as vr,interval as Gt,VideoQuality as Je,videoQualityToHeight as Er,abortable as oe,getExponentialDelay as bi,throttle as kr,isIOS as $r,CurrentClientDevice as Ar,safeStorage as Zi,fillWithDefault as wr,Logger as Dr}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as yd,Subject as Td,Subscription as vd,ValueSubject as Ed,VideoQuality as kd}from"@vkontakte/videoplayer-shared/esnext.esm.js";const Pr="2.0.98-dev.489417ae.0";var f;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(f||(f={}));var y;(function(r){r.MPEG="MPEG",r.DASH="DASH",r.DASH_SEP="DASH_SEP",r.DASH_SEP_VK="DASH_SEP",r.DASH_WEBM="DASH_WEBM",r.DASH_WEBM_AV1="DASH_WEBM_AV1",r.DASH_WEBM_VK="DASH_WEBM",r.DASH_ONDEMAND="DASH_ONDEMAND",r.DASH_ONDEMAND_VK="DASH_ONDEMAND",r.DASH_LIVE="DASH_LIVE",r.DASH_LIVE_CMAF="DASH_LIVE_CMAF",r.DASH_LIVE_WEBM="DASH_LIVE_WEBM",r.HLS="HLS",r.HLS_ONDEMAND="HLS_ONDEMAND",r.HLS_JS="HLS",r.HLS_LIVE="HLS_LIVE",r.HLS_LIVE_CMAF="HLS_LIVE_CMAF",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Be;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(Be||(Be={}));var Re;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(Re||(Re={}));var Ei;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(Ei||(Ei={}));var j;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(j||(j={}));var xt;(function(r){r.NONE="none",r.INLINE="inline",r.FULLSCREEN="fullscreen",r.SECOND_SCREEN="second_screen",r.PIP="pip"})(xt||(xt={}));var Lr=r=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class xr{connection$=new m(void 0);castState$=new m(Re.NOT_AVAILABLE);errorEvent$=new I;contentId;realCastState$=new m(Re.NOT_AVAILABLE);subscription=new se;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=P(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},s||Lr("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:x.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(){P(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Y(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Y(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(M(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 N(s.sessionState)}})).add(O(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vi(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),A(s=>s.castState)),Ne([i.getCastState()])).pipe(le(),A(Rr),vi(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const a=s===Re.CONNECTED,n=P(this.connection$.getValue());if(a&&!n){const o=i.getCurrentSession();D(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(Y(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===Re.CONNECTED?P(this.connection$.getValue())?Re.CONNECTED:Re.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:x.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Rr=r=>{switch(r){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Re.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Re.AVAILABLE;case cast.framework.CastState.CONNECTING:return Re.CONNECTING;case cast.framework.CastState.CONNECTED:return Re.CONNECTED;default:return N(r)}};var fe;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",r[r.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Oe=(r,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{const i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:N(t)}return r};const Bi=(r,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:N(e)}};var R=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class de{state;prevState;transition;transitionStarted$=new I;transitionEnded$=new I;transitionUpdated$=new I;forceChanged$=new I;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(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||P(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 Ir=r=>{switch(r){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return N(r)}};var W;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(W||(W={}));const Cr=5,_r=5,Br=500,gs=7e3;class Mr{subscription=new se;loadMediaTimeoutSubscription=new se;videoState=new de(W.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(Ir(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 se;this.subscription.add(e),this.subscription.add(O(this.videoState.stateChangeStarted$.pipe(A(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(A(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,a)=>this.subscription.add(s.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new I;e.add(s.pipe(je(Br)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===j.Applying||Math.abs(o-a)>Cr)&&s.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:a}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<_r&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,f.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:N(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(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(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.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:j.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===W.PAUSED||e===W.PLAYING)&&(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===W.PLAYING||e===W.PAUSED)&&(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.params.desiredState.playbackState.getTransition()?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY)}handleRemoteStop(){this.videoState.getState()!==W.STOPPED&&this.videoState.setState(W.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,a;switch(e){case y.MPEG:{const d=t[e];D(d);const h=br(Object.keys(d));D(h);const u=d[h];D(u),i=u,s="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const d=t[e];D(d),i=d.url,s="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const d=t[e];D(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const d=t[e];D(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const d=t[e];D(d),i=Oe(d.url),s="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:x.VIDEO_PIPELINE,message:d,thrown:h}),h}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return P(o)&&(n.metadata.title=o),P(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===j.Applying||i.state===j.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,a)=>{this.loadMediaTimeoutSubscription.add(yr(gs).subscribe(()=>a(`timeout(${gs})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:x.VIDEO_PIPELINE,message:a,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(),a=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(a)};`}),i===f.STOPPED){e!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.stop());return}if(!t){if(s?.to!==f.PAUSED&&a.state===j.Requested&&e!==W.STOPPED){this.seek(a.position/1e3);return}switch(i){case f.READY:{switch(e){case W.PLAYING:case W.PAUSED:case W.READY:break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PLAYING:{switch(e){case W.PLAYING:break;case W.PAUSED:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.READY:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case W.PLAYING:this.videoState.startTransitionTo(W.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case W.PAUSED:break;case W.READY:this.videoState.startTransitionTo(W.PAUSED),this.videoState.setState(W.PAUSED);break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}default:N(i)}}}}var Or=r=>{let e,t=!1,i=!1;r.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),r.extend("MediaSourceController",function(){const{parent:s}=this,a=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&e?.()}}},!0)},Nr=r=>{const e=new m(1/0),t=new I,i=new m(void 0),s=new m(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const S=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;P(b)&&!isNaN(b)&&e.next(b)}const l=u["x-delivery-type"]??Ei.HTTP1,p={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(l),s.next(p)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return r.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(l){if(l.request.type==="MPD"){const p=l.onload,S=l.progress;l.onload=function(...v){return c(this),p(...v)},l.progress=function(...v){return d(this),S(...v)},o()}return u(l)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},It=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Fr=r=>r.extend("RequestModifier",()=>({modifyRequestURL:It}),!0),Vr=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const nt=(r,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:a}={})=>{const n=r.getState(),o=e(),c=Y(s),d=new se;return s&&d.add(s.subscribe(h=>{const u=r.getState();i(h,u)&&r.setState(h)},a)),i(o,n)||(t(n),c&&r.setState(n)),d.add(r.stateChangeStarted$.subscribe(h=>{t(h.to),c&&r.setState(h.to)},a)),d},_t=(r,e,t)=>nt(e,()=>r.loop,i=>{P(i)&&(r.loop=i)},{onError:t}),St=(r,e,t,i)=>nt(e,()=>({muted:r.muted,volume:r.volume}),s=>{P(s)&&(r.muted=s.muted,r.volume=s.volume)},{equal:(s,a)=>s===a||s?.muted===a?.muted&&s?.volume===a?.volume,changed$:t,onError:i}),Dt=(r,e,t,i)=>nt(e,()=>r.playbackRate,s=>{P(s)&&(r.playbackRate=s)},{changed$:t,onError:i}),Ur=r=>["__",r.language,r.label].join("|"),Hr=(r,e)=>{if(r.id===e)return!0;const[t,i,s]=e.split("|");return r.language===i&&r.label===s};class ot{available$=new I;current$=new m(void 0);error$=new I;video;cueSettings;subscription=new se;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=a=>{this.error$.next({id:"TextTracksManager",category:x.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(nt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{P(a)&&this.setInternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(nt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{P(a)&&this.setExternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(nt(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:s})),this.subscription.add(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){D(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(O(M(e,"addtrack"),M(e,"removetrack"),Ne(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),le((i,s)=>i.length===s.length&&i.every(({id:a},n)=>a===s[n].id))).subscribe(this.available$)),this.subscription.add(O(M(e,"change"),Ne(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),A(i=>i&&this.htmlTextTrackToITextTrack(i).id),le()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(M(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=a=>{const n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(M(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;P(t.align)&&(s.align=t.align),P(t.position)&&(s.position=t.position),P(t.size)&&(s.size=t.size),P(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){D(this.video);const t=[...this.video.textTracks];return e?t:t.filter(ot.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Ur(e),a=this.externalTracks.has(s),n=s.includes("auto");return a?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,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:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){D(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Y(e)||!Hr(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){D(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){D(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 hs=r=>{r.removeAttribute("src"),r.load()},Yr=r=>{try{r.pause(),r.playbackRate=0,hs(r),r.remove()}catch(e){console.error(e)}};class Gr{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 ss=window.WeakMap?new WeakMap:new Gr,bt=r=>{let e=r.querySelector("video");const t=!!e;return e?hs(e):(e=document.createElement("video"),r.appendChild(e)),ss.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},yt=r=>{const e=ss.get(r);ss.delete(r),e?hs(r):Yr(r)};class Ai{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 Gs=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ss=r=>{const e=Gs(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},zr=r=>{const e=Gs(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},rs=3;class qr{_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 a=this._source.buffered.end(t);s>e&&s-e<rs&&(s=e),this._buffer.push({from:s,to:a,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||rs))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:a})=>{const n=s>=e&&s<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(s,e):s<e&&a>t?(i(t,a),i(s,e)):i(s,a))})}destroy(){this._buffer=[]}}var zs=(r,e,t=rs)=>{let i=0,s=0;for(let a=0;a<r.length;a++){const n=r.start(a),o=r.end(a);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=a-1;c>=0;c--)r.end(c)+t>=i&&(i=r.start(c));for(let c=a+1;c<r.length;c++)r.start(c)-t<=s&&(s=r.end(c))}}return{from:i,to:s}};const Tt=r=>{const e=g=>M(r,g).pipe(ti(void 0)),i=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>M(r,g))).pipe(A(g=>g.type==="ended"?r.readyState<2:r.readyState<3),le()),s=O(M(r,"progress"),M(r,"timeupdate")).pipe(A(()=>zs(r.buffered,r.currentTime))),n=Wi().browser===us.Safari?Le({play:e("play").pipe(be()),playing:e("playing")}).pipe(ti(void 0)):e("playing"),o=M(r,"volumechange").pipe(A(()=>({muted:r.muted,volume:r.volume}))),c=M(r,"ratechange").pipe(A(()=>r.playbackRate)),d=M(r,"error").pipe(K(()=>!!(r.error||r.played.length)),A(()=>{const g=r.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:x.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:r.error??void 0}})),h=M(r,"timeupdate").pipe(A(()=>r.currentTime)),u=new I,l=.3;let p;h.subscribe(g=>{r.loop&&P(p)&&P(g)&&p>=r.duration-l&&g<=l&&u.next(p),p=g});const S=M(r,"enterpictureinpicture"),v=M(r,"leavepictureinpicture"),b=new m(zr(r));S.subscribe(()=>b.next(!0)),v.subscribe(()=>b.next(!1));const w=new m(Ss(r));return M(r,"fullscreenchange").pipe(A(()=>Ss(r))).subscribe(w),{playing$:n,pause$:e("pause").pipe(K(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:M(r,"durationchange").pipe(A(()=>r.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:b,inFullscreen$:w}},ji=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let ls=!1,At={};const Wr=r=>{ls=r},Qr=()=>{At={}},jr=r=>{r(At)},Li=(r,e)=>{ls&&(At.meta=At.meta??{},At.meta[r]=e)};class ft{name;constructor(e){this.name=e}next(e){if(!ls)return;At.series=At.series??{};const t=At.series[this.name]??[];t.push([Date.now(),e]),At.series[this.name]=t}}var Vt;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(Vt||(Vt={}));const Jr=new ft("best_bitrate"),Xr=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class qs{last;history={};recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Kr='Assertion "ABR Tracks is empty array" failed',qt=(r,{container:e,throughput:t,tuning:i,limits:s,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{Tr(r,Kr);const l=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*i.containerSizeFactor,height:e.height*l*i.containerSizeFactor},S=p&&Ct(p),v=i.considerPlaybackRate&&P(o)?o:1,b=r.filter(T=>!Yt(T.quality)).sort((T,V)=>ei(T.quality,V.quality)?-1:1),w=b.at(-1)?.quality,C=b.at(0)?.quality,g=Y(s)||P(s.min)&&P(s.max)&&Ci(s.max,s.min)||P(s.min)&&C&&ei(s.min,C)||P(s.max)&&w&&Ci(s.max,w),E=v*Xr(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},q=b.filter(T=>(S?Ci(T.quality,S):!0)?(P(t)&&isFinite(t)&&P(T.bitrate)?t-a>=T.bitrate*E:!0)?i.lazyQualitySwitch&&P(i.minBufferToSwitchUp)&&c&&!Yt(c.quality)&&(n??0)<i.minBufferToSwitchUp&&ei(T.quality,c.quality)?(L[T.quality]=Vt.Buffer,!1):!!h&&is(T.quality,h)?(L[T.quality]=Vt.DroppedFramesLimit,!1):g||(Y(s.max)||Ys(T.quality,s.max))&&(Y(s.min)||is(T.quality,s.min))?!0:(L[T.quality]=Vt.FitsQualityLimits,!1):(L[T.quality]=Vt.FitsThroughput,!1):(L[T.quality]=Vt.FitsContainer,!1))[0];q&&q.bitrate&&Jr.next(q.bitrate);const F=q??b[Math.ceil((b.length-1)/2)]??r[0];F.quality!==d?.last?.quality&&u({message:`
7
7
  [available tracks]
8
8
  ${r.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
9
9
  `)}
@@ -19,28 +19,28 @@ import{ValueSubject as g,Subject as I,Subscription as se,isNonNullable as P,Erro
19
19
  playbackRate: ${o},
20
20
  playbackRateFactor: ${v},
21
21
  forwardBufferHealth: ${n},
22
- bitrateFactor: ${$},
22
+ bitrateFactor: ${E},
23
23
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
24
24
  droppedVideoMaxQualityLimit: ${h},
25
- limitsAreInvalid: ${m},
25
+ limitsAreInvalid: ${g},
26
26
  maxQualityLimit: ${s?.max},
27
27
  minQualityLimit: ${s?.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(x).map(([T,V])=>`${T}: ${V}`).join(`
30
+ ${Object.entries(L).map(([T,V])=>`${T}: ${V}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
33
  [best track] ${q?.quality}
34
34
  [selected track] ${F?.quality}
35
35
  `});const G=F&&d&&d.history[F.id]&&ne()-d.history[F.id]<=i.trackCooldown&&(!d.last||F.id!==d.last.id);if(F?.id&&d&&!G&&d.recordSelection(F),G&&d?.last){const T=d.last;return d?.recordSwitch(T),u({message:`
36
36
  [last selected] ${T?.quality}
37
- `}),T}return d?.recordSwitch(F),F};var Ne=r=>new URL(r).hostname;const ea=300,Ei=(r,e=ea)=>new Qi(t=>{const{width:i,height:s}=r.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const a=new ResizeObserver(Dr(n=>{const o=n[0];if(!o)return;let c,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,c=o.contentBoxSize[0].inlineSize):o.contentRect&&(c=o.contentRect.width,d=o.contentRect.height),P(c)&&P(d)&&t.next({width:c,height:d})},e));return a.observe(r),()=>a.disconnect()});class Ai{onDroopedVideoFramesLimit$=new I;subscription=new se;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new I;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(M(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Gt(this.droppedFramesChecker.checkTime).pipe(K(()=>this.playing),K(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Qe(this.droppedFramesChecker.checkTime)),i=O(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&&!Yt(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,a=1-(i-s)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&ei(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])=>Ii(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 hi={};var X;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(X||(X={}));const Ee=(r,e)=>new Qi(t=>{const i=s=>t.next(s);return r.on(e,i),()=>r.off(e,i)});class bs{subscription=new se;videoState=new de(X.DOWNLOADING_LIB);video;player;params;textTracksManager=new ot;droppedFramesManager=new Ai;videoTracks$=new g([]);frameRatesByFrameHeight={};isLive$=new g(void 0);maxSeekBackTime$=new g(1/0);availableFrom$=new g(void 0);elementSize$=new g(void 0);liveOffset=new $i;constructor(e){this.video=bt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:L.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||(hi.MediaPlayer=s.MediaPlayer,hi.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){w(hi.MediaPlayer,"dashjs not loaded"),w(hi.Debug,"dashjs not loaded"),this.player=hi.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?ji(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Ur(this.player),Nr(this.player),this.params.tuning.requestQuick&&Vr(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,$)=>this.subscription.add(m.subscribe($,i));s(Ei(this.video),this.elementSize$),s(Ee(this.player,"error").pipe(A(m=>{const $=typeof m.error=="object"?m.error.code:m.error,x=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${$}`,message:x}})),e.error$),s(Ee(this.player,"playbackError").pipe(A(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=Ee(this.player,"qualityChangeRendered").pipe(K(({mediaType:m})=>m==="video"),A(({newQuality:m})=>this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===m)?.track));a.pipe(K(P)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(K(({to:m})=>m===X.STREAM_INITIALIZED),be()).subscribe(()=>{this.subscription.add(nt(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===m)?.track},m=>{if(Y(m))return;const $=this.videoTracks$.getValue().find(({track:x})=>x.id===m.id)?.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a,onError:i}))},i)),this.subscription.add(nt(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),s(Ee(this.player,"bufferStateChanged").pipe(K(({mediaType:m})=>m==="video"),A(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(Ee(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:$}})=>{const x=this.player.getDashMetrics(),H=x.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),q=x.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??vi.HTTP1,F={1:!0,0:!1}[H]??void 0;this.params.output.httpConnectionType$.next(q),this.params.output.httpConnectionReused$.next(F),e.hostname$.next(Ne($))}),s(Ee(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:$,availableFrom:x}}})=>{this.isLive$.next($),this.availableFrom$.next(x.getTime()),$||e.duration$.next(m);const H=[],q=this.player.getQualityFor("video");let F;for(const G of this.player.getBitrateInfoListFor("video")){const T=G.qualityIndex.toString(10),V=Ct(G),z=G.bitrate/1e3,te={width:G.width,height:G.height},ye=this.frameRatesByFrameHeight[G.height];if(V){const ke={id:T,quality:V,bitrate:z,size:te,fps:ye};H.push({track:ke,bitrateInfo:G}),G.qualityIndex===q&&(F=ke)}}this.videoTracks$.next(H),e.availableVideoTracks$.next(H.map(({track:G})=>G)),F&&e.currentVideoTrack$.next(F),this.videoState.setState(X.STREAM_INITIALIZED),this.videoState.startTransitionTo(X.READY)}),s(Ee(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const $=m.requestEndDate.getTime()-m.firstByteDate.getTime(),x=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(x,$)}),s(O(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(),$=qt(this.videoTracks$.getValue().map(({track:q})=>q),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),x=t.autoVideoTrackLimits.getTransition();x&&e.autoVideoTrackLimits$.next(x.to);const H=this.videoTracks$.getValue().find(({track:q})=>q===$);H?.bitrateInfo&&this.player.setQualityFor("video",H?.bitrateInfo.qualityIndex,!1)}),s(xe({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(K(P))}).pipe(K(({isLive:m})=>m),A(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=Ee(this.player,"playbackTimeUpdated").pipe(A(({time:m})=>m??0));s(xe({availableFrom:this.availableFrom$.pipe(K(P)),currentTime:n}),({availableFrom:m,currentTime:$})=>this.params.output.liveTime$.next(m+$*1e3)),s(n.pipe(K(()=>this.isLive$.getValue()===!1)),e.position$),s(Ee(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(Ee(this.player,"playbackEnded"),e.endedEvent$),s(Ee(this.player,"playbackProgress").pipe(A(()=>zs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(Ee(this.player,"playbackPlaying"),()=>{this.videoState.setState(X.PLAYING),R(t.playbackState,f.PLAYING)}),s(Ee(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(Ee(this.player,"playbackPaused"),()=>{this.videoState.setState(X.PAUSED),R(t.playbackState,f.PAUSED)}),s(Ee(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===X.READY&&this.videoState.setState(X.READY)}),s(this.isLive$,e.isLive$),s(Ei(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=Fr(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(be()),e.firstBytesEvent$),s(Ee(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(xe({isLive:this.isLive$,isShort:e.duration$.pipe(A(m=>m<60))}),({isLive:m,isShort:$})=>{const x=!m&&$;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:x}}})}),s(n.pipe(K(m=>m>this.params.tuning.insufficientBufferRuleMargin),be()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Ee(this.player,"manifestLoaded").pipe(be()).subscribe(()=>{this.subscription.add(Ee(this.player,"playbackPlaying").pipe(be(),ti(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(Ee(this.player,"manifestLoaded"),m=>{if(m.data?.Period?.AdaptationSet){const $=[];for(const x of m.data?.Period?.AdaptationSet)if(x.contentType==="text"){const H=x.Representation?.id,q=new URL(x.Representation?.BaseURL,m.data?.baseUri).toString(),F="internal",G=x.lang;$.push({id:H,url:q,type:F,language:G})}t.internalTextTracks.startTransitionTo($)}}),this.subscription.add(_t(this.video,t.isLooped,i));const{volumeState$:l,looped$:p,playbackRateState$:S,inPiP$:v,inFullscreen$:b,pause$:D,playing$:C}=Tt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:C,pause$:D,tracks$:this.videoTracks$.pipe(A(m=>m.map(({track:$})=>$)))}),this.subscription.add(St(this.video,t.volume,l,i)),this.subscription.add(l.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Dt(this.video,t.playbackRate,S,i)),this.subscription.add(v.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(X.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(X.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=Me(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,fe.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(X.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(X.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(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===X.DOWNLOADING_LIB||e===X.STREAM_INITIALIZED))switch(i?.to!==f.PAUSED&&s.state===j.Requested&&e!==X.STOPPED&&t!==f.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case f.STOPPED:{switch(e){case X.STOPPED:break;case X.PLAYING:case X.PAUSED:case X.READY:this.stop();break;default:N(e)}break}case f.READY:{switch(e){case X.STOPPED:this.prepare();break;case X.PLAYING:case X.PAUSED:case X.READY:break;default:N(e)}break}case f.PLAYING:{switch(e){case X.PLAYING:break;case X.PAUSED:a&&(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 X.READY:this.play();break;case X.STOPPED:this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case X.PLAYING:this.pause(),this.liveOffset.pause();break;case X.PAUSED:break;case X.READY:this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case X.STOPPED:this.prepare();break;default:N(e)}break}default:N(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}yt(this.video),this.params.output.element$.next(void 0)}}var oi=r=>{switch(r){case"mobile":return je.Q_144P;case"lowest":return je.Q_240P;case"low":return je.Q_360P;case"sd":case"medium":return je.Q_480P;case"hd":case"high":return je.Q_720P;case"fullhd":case"full":return je.Q_1080P;case"quadhd":case"quad":return je.Q_1440P;case"ultrahd":case"ultra":return je.Q_2160P}};const ys=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Pt=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!ys(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return ys(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function Be(){return ne()}function Ws(r){return Be()-r}function Ts(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,c=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return c&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ta(r,e,t){const i=(...s)=>{t.apply(null,s),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ci(r,e,t,i){const s=window.XMLHttpRequest;let a,n,o,c=!1,d=0,h,u,l=!1,p="arraybuffer",S=7e3,v=2e3,b=()=>{if(c)return;w(h);const z=Ws(h);let te;if(z<v){te=v-z,setTimeout(b,te);return}v*=2,v>S&&(v=S),n&&n.abort(),n=new s,H()};const D=z=>(a=z,V),C=z=>(u=z,V),m=()=>(p="json",V),$=()=>{if(!c){if(--d>=0){b(),i&&i();return}c=!0,u&&u(),t&&t()}},x=z=>(l=z,V),H=()=>{h=Be(),n=new s,n.open("get",r);let z=0,te,ye=0;const ke=()=>(w(h),Math.max(h,Math.max(te||0,ye||0)));if(a&&n.addEventListener("progress",U=>{const re=Be();a.updateChunk&&U.loaded>z&&(a.updateChunk(ke(),U.loaded-z),z=U.loaded,te=re)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(c)return;w(n);const U=n.status;if(U>=200&&U<300){if(n.response.byteLength&&a){const re=n.response.byteLength-z;re&&a.updateChunk&&a.updateChunk(ke(),re)}u&&u(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),l){const U=()=>{w(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=Be(),n.removeEventListener("readystatechange",U))};n.addEventListener("readystatechange",U)}return n.responseType=p,n.send(),V},V={withBitrateReporting:D,withParallel:x,withJSONResponse:m,withRetryCount:z=>(d=z,V),withRetryInterval:(z,te)=>(P(z)&&(v=z),P(te)&&(S=te),V),withTimeout:z=>(o=z,V),withFinally:C,send:H,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return V}const ia=100,sa=2e3,ra=500;let aa=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-ra;if(t-e>sa){let i=0,s=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,s+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const c=a.bytes*n/o;s+=c,a.start=t,a.bytes-=c}}}if(s>0&&i>0){const a=s*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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>ia&&(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 na{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}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=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=c=>{e._complete=1,e._responseData=c,e._downloadTime=Be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ci(t,a,()=>s("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),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 a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}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 xi=1e4,Li=3,oa=300,da=2e3,ca=6e4,ua=10,ha=1,la=500;class fa{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 aa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ts(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=Ts(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,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||P(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:a}=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 n=()=>{ta(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new na(Li,xi,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 a=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const $=a&&(!h||h===this.rep);return $||t("Not running!"),$},l=($,x,H)=>{c&&c.abort(),c=Ci(this.urlResolver.resolve($,!1),x,H,()=>this._retryCallback()).withTimeout(xi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Li).withFinally(()=>{c=null}).send()},p=($,x,H)=>{w(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),x,H,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=$=>{const x=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${x}=>${$}`),i.playbackRate=$)},v=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const H=Be()-1e4;let q=0;for(let G=0;G<this.bufferStates.length;G++){const T=this.bufferStates[G];$=Math.min($,T.buf),T.ts<H&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${$} drop=${q} jitter=${this.sourceJitter}`);let F=$-ha;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?S(1.15):F>1?S(1.1):F>.3?S(1.05):S(1)}},D=$=>{let x;const H=()=>x&&x.start?x.start.length:0,q=U=>x.start[U]/1e3,F=U=>x.dur[U]/1e3,G=U=>x.fragIndex+U,T=(U,re)=>({chunkIdx:G(U),startTS:q(U),dur:F(U),discontinuity:re}),V=()=>{let U=0;if(x&&x.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,pe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,$e=re;this.sourceJitter>1&&($e+=this.sourceJitter-1);let Ce=x.dur.length-1;for(;Ce>=0&&($e-=x.dur[Ce],!($e<=0));--Ce);U=Math.min(Ce,x.dur.length-1-pe),U=Math.max(U,0)}return T(U,!0)},z=U=>{const re=H();if(!(re<=0)){if(P(U)){for(let pe=0;pe<re;pe++)if(q(pe)>U)return T(pe)}return V()}},te=U=>{const re=H(),pe=U?U.chunkIdx+1:0,$e=pe-x.fragIndex;if(!(re<=0)){if(!U||$e<0||$e-re>ua)return t(`Resync: offset=${$e} bChunks=${re} chunk=`+JSON.stringify(U)),V();if(!($e>=re))return T(pe-x.fragIndex,!1)}},ye=(U,re,pe)=>{d&&d.abort(),d=Ci(this.urlResolver.resolve(U,!0,this.lowLatency),re,pe,()=>this._retryCallback()).withTimeout(xi).withRetryCount(Li).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(U,re)=>{ye($,pe=>{if(!u())return;x=pe;const $e=!!x.lowLatency;$e!==this.lowLatency&&v($e);let Ce=0;for(let dt=0;dt<x.dur.length;++dt)Ce+=x.dur[dt];Ce>0&&(w(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ce/x.dur.length)),s({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,U(z(re))},()=>this._handleNetworkError())},nextChunk:te}},C=()=>{a=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),w(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:$=>{const{videoElement:x,logger:H}=this.params;let q=D(e.jidxUrl),F,G,T,V,z=0,te,ye,ke;const U=()=>{te&&(clearTimeout(te),te=void 0);const ae=Math.max(la,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=z+ae,Fe=Be(),De=Math.min(1e4,we-Fe);z=Fe;const Et=()=>{d||u()&&q.seek(()=>{u()&&(z=Be(),re(),U())})};De>0?te=window.setTimeout(()=>{this.paused?U():Et()},De):Et()},re=()=>{let ae;for(;ae=q.nextChunk(V);)V=ae,ci(ae);const we=q.nextChunk(T);if(we){if(T&&we.discontinuity){H("Detected discontinuity; restarting playback"),this.paused?U():(C(),this._initPlayerWith(e));return}dt(we)}else U()},pe=(ae,we)=>{if(!u()||!this.sourceBuffer)return;let Fe,De,Et;const Te=Ye=>{window.setTimeout(()=>{u()&&pe(ae,we)},Ye)};if(this.sourceBuffer.updating)H("Source buffer is updating; delaying appendBuffer"),Te(100);else{const Ye=Be(),Ae=x.currentTime;!this.paused&&x.buffered.length>1&&ye===Ae&&Ye-ke>500&&(H("Stall suspected; trying to fix"),this._fixupStall()),ye!==Ae&&(ye=Ae,ke=Ye);const Pe=this._getBufferSizeSec();if(Pe>30)H(`Buffered ${Pe} seconds; delaying appendBuffer`),Te(2e3);else try{this.sourceBuffer.appendBuffer(ae),this.videoPlayStarted?(this.bufferStates.push({ts:Ye,buf:Pe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(ct){if(ct.name==="QuotaExceededError")H("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(Fe=this.sourceBuffer.buffered.start(0),De=Ae,De-Fe>4&&this.sourceBuffer.remove(Fe,De-3)),Te(1e3);else throw ct}}},$e=()=>{G&&F&&(H([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(T)]),pe(G,function(){G=null,re()}))},Ce=ae=>e.fragUrlTemplate.replace("%%id%%",ae.chunkIdx),dt=ae=>{u()&&p(Ce(ae),(we,Fe)=>{if(u()){if(Fe/=1e3,G=we,T=ae,n=ae.startTS,Fe){const De=Math.min(10,ae.dur/Fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}$e()}},()=>this._handleNetworkError())},ci=ae=>{u()&&(w(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ce(ae),!1)))},Wt=ae=>{u()&&(e.cachedHeader=ae,pe(ae,()=>{F=!0,$e()}))};a=!0,q.seek(ae=>{if(u()){if(z=Be(),!ae){U();return}V=ae,!Y($)||ae.startTS>$?dt(ae):(T=ae,re())}},$),e.cachedHeader?Wt(e.cachedHeader):l(e.headerUrl,Wt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),P(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,w(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return P(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let l,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(p=this._getBufferSizeSec(),S=u/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}l=this._selectQuality(u),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${u}`)},a=(()=>({updateChunk:(l,p)=>{const S=Be();if(this.chunkRateEstimator.addInterval(l,S,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-l,speed:b}),!0}},get:()=>{const l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=a.get();if(u&&o&&this.autoQuality){if(c&&u>o&&Ws(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,l)=>{const p=a.updateChunk(u,l);return p&&d(),p},notifySwitch:u=>{const l=Be();u<o&&(n=l),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=Ci(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(xi).withRetryCount(Li).withRetryInterval(oa,da).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Pt(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,a=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&s.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=d,o.push(c))}),o.sort(function(c,d){return c.video&&d.video?d.video.height-c.video.height:d.bitrate-c.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(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))},ca))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var J;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(J||(J={}));const pa=[J.PAUSED,J.PLAYING,J.READY],ma=[J.PAUSED,J.PLAYING,J.READY];class ga{subscription=new se;video;videoState=new de(J.STOPPED);dash;representations$=new g([]);textTracksManager=new ot;droppedFramesManager=new Ai;maxSeekBackTime$=new g(1/0);zeroTime$=new g(void 0);liveOffset=new $i;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:L.WTF,message:"DashLiveProvider internal logic error",thrown:s})};O(this.videoState.stateChangeStarted$.pipe(A(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(s)}`})}),this.video=bt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Tt(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(A(s=>s.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(J.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(le(),A(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(xe({zeroTime:this.zeroTime$.pipe(K(P)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:a})=>this.params.output.liveTime$.next(s+a*1e3),t)).add(_t(this.video,this.params.desiredState.isLooped,t)).add(St(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Dt(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 a=s&&vr(s);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case J.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(f.STOPPED);break;case J.MANIFEST_READY:case J.READY:this.params.desiredState.playbackState.getTransition()?.to===f.READY&&this.params.desiredState.playbackState.setState(f.READY);break;case J.PAUSED:this.params.desiredState.playbackState.setState(f.PAUSED);break;case J.PLAYING:this.params.desiredState.playbackState.setState(f.PLAYING);break;default:return N(s.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Oe(["init"])).pipe(Qe(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),yt(this.video)}createLiveDashPlayer(){const e=new fa({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&&P(t)?t:qt(e.map(({track:d})=>d),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=s?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(n||a!==o)&&this.setVideoTrack(s),c&&this.setAutoQuality(i),n||c||a!==o){const d=e.find(({track:h})=>h.id===a)?.representation;w(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;w(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===f.PAUSED&&i===J.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Me(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,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:L.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const a=s.name??s.index.toString(10),n=oi(s.name)??Ct(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:a,quality:n,bitrate:o,size:c};i.push({track:d,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===J.MANIFEST_READY&&this.videoState.setState(J.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),P(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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(J.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ma.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==f.PAUSED&&a.state===j.Requested&&pa.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_READY),this.dash.attachSource(Me(this.params.source.url));return;case J.MANIFEST_READY:this.videoState.startTransitionTo(J.READY),this.prepare();break;case J.READY:if(i===f.PAUSED)this.videoState.setState(J.PAUSED);else if(i===f.PLAYING){this.videoState.startTransitionTo(J.PLAYING);const c=s?.from;c&&c===f.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(J.PAUSED)})}return;case J.PLAYING:i===f.PAUSED&&(this.videoState.startTransitionTo(J.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case J.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(J.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(J.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Me(this.params.source.url,c))}return;default:return N(e)}}}var fs=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?vi.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},He=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){const s=r.start(i)*1e3,a=r.end(i)*1e3;s<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Sa=r=>{const e=document.createElement("a");return e.href=r,e.origin},ba=r=>{const e=document.createElement("a");return e.href=r,e.host};class Qs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,a,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=n,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(ba(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 Mi{_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 a=0;for(let n=0,o=s.length;n<o;n++)a+=s.end(n)-s.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,a,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,l=0;const p=v=>{s(Mi._str2ua(v.substr(c))),c=v.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=It(S)),this._lastXhr=new Qs(S,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const b=Date.now()-d;this._params.onBandwidthChange({size:v.length,duration:b,speed:8*v.length/(b/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),a?.()},v=>{if(v.length-c>o&&p(v),u===0){u=Date.now();return}l=v.length-h;const b=Date.now()-u;l>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:l,duration:b,speed:8*l/(b/1e3)}),l=0,h=v.length,u=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},n,(v,b,D)=>this._params.onError(v,b,D))})}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=Mi._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 ya{_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=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},s=t.exec(e),a=s?.[1]==="-"?-1:1,n={years:i(s?.[2],a),months:i(s?.[3],a),weeks:i(s?.[4],a),days:i(s?.[5],a),hours:i(s?.[6],a),minutes:i(s?.[7],a),seconds:i(s?.[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=It(i)),new Qs(i,t,s=>{this.attachManifest(s,t,Sa(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,a,n)=>this._params.onError(s,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,h)=>{const u=d.attributes.getNamedItem(h);return u?u.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),l=h&&h.getElementsByTagName("Initialization")[0],p=l&&n(l,"range").split("-");if(!p||!u){const m=d.parentElement;if(m?.getAttribute("contentType")==="text"){const $=d.getAttribute("id")??void 0,x=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,H=m.getAttribute("lang")??void 0;x&&c.push({id:$,url:x,language:H})}return}const S=.1,v=Number(d.attributes.getNamedItem("bandwidth")?.value),b=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let D;const C=d.attributes.getNamedItem("frameRate")?.value??void 0;D=C?ji(C):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:v,baseURL:b,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:D,bufferSize:S*v/8,bufferLength:S,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:h,url:u})=>{const l=document.createElement("track");u&&l.setAttribute("src",u),d&&l.setAttribute("id",d),h&&l.setAttribute("srclang",h),this._video.appendChild(l)}),this._representations.sort((d,h)=>h.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:c})}_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 a=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,a);const n=new DataView(s.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let c=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const h=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let l=0;l<h;l+=1){const p=d+(n.getUint32(a,!1)&2147483647),S=c+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:c/o,toTime:S/o,fromOffset:d,toOffset:p-1}),d=p,c=S}const u=e.refs[e.refs.length-1];u.toTime-u.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,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||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(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}u=p.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},u*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},c=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Mi({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",c),i.removeEventListener("webkitsourceopen",c)};i.addEventListener("sourceopen",c,!1),i.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-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 a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),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 a=.1;if(s.toTime<i.to+a){const n=this._findRef(s.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,n.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,(o,c)=>this._stream.remove(o,c)),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||Y(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 a=t[s];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!i||a.fromTime<i.fromTime)&&(i=a)}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 Z;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Z||(Z={}));const Ta=[Z.PAUSED,Z.PLAYING];class va{videoState=new de(Z.STOPPED);subscription=new se;video;buffer;dash;representations$=new g([]);currentRepresentation$=new g(void 0);params;textTracksManager=new ot;droppedFramesManager=new Ai;elementSize$=new g(void 0);dashLiteEvents={idxRequestPing$:new I,responseHeaders$:new I,manifestReady$:new I,representationPlay$:new I,error$:new I};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),O(this.videoState.stateChangeStarted$.pipe(A(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=bt(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Wr(this.video),this.dash=new ya({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:L.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=o=>{e.error$.next({id:"DashProvider",category:L.WTF,message:"DashProvider internal logic error",thrown:o})},s=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},a=Tt(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{Y(this.params.desiredState.seekState.getState().state!==j.Applying)&&(this.videoState.getState()===Z.PLAYING||this.videoState.getState()===Z.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(St(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dt(this.video,t.playbackRate,a.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$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(A(o=>o.map(({track:c})=>c)))}),n(Ei(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Z.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(A(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(O(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$,M(this.video,"progress")).pipe(A(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState()?.id,u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),p=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let S;if(!p&&P(h))S=h;else{const v=He(this.video.buffered,this.video.currentTime*1e3),b=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,D=Math.min(v/b,1);S=qt(c.map(({track:m})=>m),{container:l,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:D,playbackRate:this.video.playbackRate,current:c.find(({representation:m})=>m===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const C=t.autoVideoTrackLimits.getTransition();C&&e.autoVideoTrackLimits$.next(C.to)}return P(S)?c.find(({track:v})=>v.id===S)?.representation:void 0}),le()).subscribe(this.currentRepresentation$,i)).add(xe({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(K(o=>o.to===Z.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(K(P))}).pipe(be()).subscribe(()=>this.videoState.setState(Z.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(K(P),le((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=He(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!s())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ne(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=fs(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(be(),ti(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(K(P)).subscribe(this.handleRepresentationPlay,i)).add(O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(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),yt(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 N(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const a=s.name??s.id??s.height.toString(10),n=(s.name&&oi(s.name))??Ct(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:a,quality:n,bitrate:o,size:c,fps:d};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 a of t){const n=a.id||`${a.language}_${Date.now()}`;s.push({id:n,type:"internal",url:a.url||"",language:a.language,isAuto:a.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(Z.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 w(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(){Pt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.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(Z.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(!t)switch(s?.to!==f.PAUSED&&a.state===j.Requested&&Ta.includes(e)&&this.seek(a.position,a.forcePrecise),e){case Z.STOPPED:this.videoState.startTransitionTo(Z.MANIFEST_LOADED),this.prepare();return;case Z.MANIFEST_LOADED:this.videoState.startTransitionTo(Z.INITIAL_REPRESENTATION_SELECTED);return;case Z.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Z.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Z.METADATA_LOADED:this.videoState.startTransitionTo(Z.READY),this.dash.updateRefsForCurrentTime();return;case Z.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Z.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}var Re;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Re||(Re={}));var Oi;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Oi||(Oi={}));var Ke;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Ke||(Ke={}));var ee;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(ee||(ee={}));var ii;(function(r){r.MP4="mp4",r.WEBM="webm"})(ii||(ii={}));var Ni;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Ni||(Ni={}));var me;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(me||(me={}));class vs{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,a=i.length;s<a;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,a=i.length;s<a;s++){const n=i[s];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class js extends vs{constructor(){super(),this.listeners||vs.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 Js=class{constructor(){Object.defineProperty(this,"signal",{value:new js,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&&(Js.prototype[Symbol.toStringTag]="AbortController",js.prototype[Symbol.toStringTag]="AbortSignal");function Xs(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Ea(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=r;if(!Xs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||s)&&(a=function(d,h){let u;h&&h.signal&&(u=h.signal,delete h.signal);const l=new t(d,h);return u&&Object.defineProperty(l,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),l},a.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const h=a&&a.prototype.isPrototypeOf(c)?c.signal:d?d.signal:void 0;if(h){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(h.aborted)return Promise.reject(u);const l=new Promise((p,S)=>{h.addEventListener("abort",()=>S(u),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([l,n(c,d)])}return n(c,d)},Request:a}}const Ji=Xs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ks=Ji?Ea({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,zt=Ji?Ks.fetch:window.fetch;Ji?Ks.Request:window.Request;const et=Ji?Js:window.AbortController;var si=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const ka=(r,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-s-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},$a=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Fi=$a?ka:window.requestIdleCallback,Aa=16;let Zs=!1;try{Zs=Wi().browser===us.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Aa}catch(r){console.error(r)}let wa=class{bufferFull$=new I;error$=new I;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 a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Zs&&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:L.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:L.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:N(t)}}};var Vi=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};let vt=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}},er=class extends vt{},Da=class extends vt{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}}},Pa=class extends vt{parseChildrenBoxes(){return di(this.content)}},xa=class extends vt{data;constructor(e){super(e),this.data=this.content}},wi=class extends vt{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},La=class extends wi{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,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}},Ra=class extends vt{parseChildrenBoxes(){return di(this.content)}},Ia=class extends vt{parseChildrenBoxes(){return di(this.content)}};var Ut;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ut||(Ut={}));let Ca=class extends wi{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ut.MONOSCOPIC;break;case 1:this.stereoMode=Ut.TOP_BOTTOM;break;case 2:this.stereoMode=Ut.LEFT_RIGHT;break;case 3:this.stereoMode=Ut.STEREO_CUSTOM;break;case 4:this.stereoMode=Ut.RIGHT_LEFT;break}this.cursor+=1}},_a=class extends wi{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},Ba=class extends wi{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},Ma=class extends vt{parseChildrenBoxes(){return di(this.content)}},Oa=class extends wi{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()}},Na=class extends vt{parseChildrenBoxes(){return di(this.content)}},Fa=class extends vt{parseChildrenBoxes(){return di(this.content)}};const Va={ftyp:Da,moov:Pa,mdat:xa,sidx:La,trak:Ra,mdia:Ma,tkhd:Oa,minf:Na,sv3d:Ia,st3d:Ca,prhd:_a,proj:Fa,equi:Ba,unknown:er};let Ua=class{createBox(e,t){const i=Va[e];return i?new i(t):new er(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Xi.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Xi=new Ua;function gi(r,e){const t=new TextDecoder("ascii");let i=r.byteOffset,s=[];for(;i<r.byteLength;){const a=t.decode(new DataView(r.buffer,i,1));if(a===e[s.length]?s.push(a):s=[],s.length===4&&s.join("")===e){const o=new DataView(r.buffer,i-7,4).getUint32(0);return i-7+o>r.byteLength?null:Xi.createBox(e,new DataView(r.buffer,i-7))}i++}return null}function Ha(r,e){const t=[];let i=0;for(;i<r.byteLength;){const s=gi(new DataView(r.buffer,r.byteOffset+i,r.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function di(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Xi.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Ya=new TextDecoder("ascii"),Ga=r=>Ya.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",za=r=>{const e=Xi.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:ee.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},qa=r=>{const e=Ha(r,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(r.buffer,r.byteOffset,t)}return null},Wa=r=>{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(gi(r,"sv3d")){e.is3dVideo=!0;const i=gi(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=gi(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=gi(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Qa={validateData:Ga,parseInit:Wa,getIndexRange:()=>{},parseSegments:za,parseFeedableSegmentChunk:qa};var E;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(E||(E={}));var _;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(_||(_={}));const Es={[E.EBML]:{type:_.Master},[E.EBMLVersion]:{type:_.UnsignedInteger},[E.EBMLReadVersion]:{type:_.UnsignedInteger},[E.EBMLMaxIDLength]:{type:_.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[E.DocType]:{type:_.String},[E.DocTypeVersion]:{type:_.UnsignedInteger},[E.DocTypeReadVersion]:{type:_.UnsignedInteger},[E.Void]:{type:_.Binary},[E.Segment]:{type:_.Master},[E.SeekHead]:{type:_.Master},[E.Seek]:{type:_.Master},[E.SeekID]:{type:_.Binary},[E.SeekPosition]:{type:_.UnsignedInteger},[E.Info]:{type:_.Master},[E.TimestampScale]:{type:_.UnsignedInteger},[E.Duration]:{type:_.Float},[E.Tracks]:{type:_.Master},[E.TrackEntry]:{type:_.Master},[E.Video]:{type:_.Master},[E.Projection]:{type:_.Master},[E.ProjectionType]:{type:_.UnsignedInteger},[E.ProjectionPrivate]:{type:_.Master},[E.Chapters]:{type:_.Master},[E.Cluster]:{type:_.Master},[E.Timestamp]:{type:_.UnsignedInteger},[E.SilentTracks]:{type:_.Master},[E.SilentTrackNumber]:{type:_.UnsignedInteger},[E.Position]:{type:_.UnsignedInteger},[E.PrevSize]:{type:_.UnsignedInteger},[E.SimpleBlock]:{type:_.Binary},[E.BlockGroup]:{type:_.Master},[E.EncryptedBlock]:{type:_.Binary},[E.Attachments]:{type:_.Master},[E.Tags]:{type:_.Master},[E.Cues]:{type:_.Master},[E.CuePoint]:{type:_.Master},[E.CueTime]:{type:_.UnsignedInteger},[E.CueTrackPositions]:{type:_.Master},[E.CueTrack]:{type:_.UnsignedInteger},[E.CueClusterPosition]:{type:_.UnsignedInteger},[E.CueRelativePosition]:{type:_.UnsignedInteger},[E.CueDuration]:{type:_.UnsignedInteger},[E.CueBlockNumber]:{type:_.UnsignedInteger},[E.CueCodecState]:{type:_.UnsignedInteger},[E.CueReference]:{type:_.Master},[E.CueRefTime]:{type:_.UnsignedInteger}},tr=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ui(r,t),s=i in Es,a=s?Es[i].type:_.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Ui(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Ui=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},pt=(r,e)=>{switch(e){case _.SignedInteger:return r.getInt8(0);case _.UnsignedInteger:return Ui(r);case _.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(r);case _.UTF8:return new TextDecoder("utf-8").decode(r);case _.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case _.Master:return r;case _.Binary:return r;default:N(e)}},ri=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=tr(i);if(!e(s))return;s.type===_.Master&&ri(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},ja=r=>{if(r.getUint32(0)!==E.EBML)return!1;let e,t,i;const s=tr(r);return ri(s.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=pt(o,n):a===E.DocType?t=pt(o,n):a===E.DocTypeReadVersion&&(i=pt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},ir=[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],Ja=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],Xa=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ri(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===E.SeekID){const b=pt(S,p);d=Ui(b)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?i=pt(S,p):l===E.Duration?s=pt(S,p):l===E.SeekPosition&&d===E.Cues?c=pt(S,p):l===E.Tracks?ri(S,({tag:b,type:D,value:C})=>b===E.ProjectionType?(h=pt(C,D)===1,!1):!0):a&&n&&ir.includes(l)&&(o=!0),!o}),w(e,"Failed to parse webm Segment start"),w(t,"Failed to parse webm Segment end"),w(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:c,is3dVideo:h,stereoMode:u,projectionType:Ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ka=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Za=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ri(r,({tag:o,type:c,value:d})=>{switch(o){case E.Cues:t=!0;break;case E.CuePoint:n&&s(n)&&a.push(n),n={};break;case E.CueTime:n&&(n.time=pt(d,c));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=pt(d,c));break;default:t&&ir.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:ee.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},en=r=>{let e=0,t=!1;try{ri(r,i=>i.tag===E.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ja.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},tn={validateData:ja,parseInit:Xa,getIndexRange:Ka,parseSegments:Za,parseFeedableSegmentChunk:en},sr=1e4,sn=3e4,rn=5e3,an=sr,nn=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?oi(a):void 0)??Ct({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},on=({id:r,bitrate:e})=>({id:r,bitrate:e}),dn=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},cn=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),Ri=r=>{const e=[];let t=0,i=r.length-1;for(;t<sr&&i>=0;)e.unshift(r[i]),t+=r[i].time.to-r[i].time.from,i--;return e};let ks=class{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);playingRepresentationInit$=new g(void 0);error$=new I;gaps=[];isSeekingLive=!1;subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new et;destroyAbortController=new et;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,s,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1,manifest:d}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!d?.dynamic,this.container=i,i){case ii.MP4:this.containerParser=Qa;break;case ii.WEBM:this.containerParser=tn;break;default:N(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=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);w(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new wa(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Vi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);w(i,"No init buffer for starting representation"),w(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(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);w(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),w(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 a=this.getCurrentPosition();P(a)&&(this.searchGaps(i,t),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(w(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=He(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Vi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=He(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===ee.FED&&!o.length&&He(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}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;P(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=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d)return;const h=Ri(d.segmentReference.segments);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);w(i);const s=Ri(i.segmentReference.segments),a=this.initData.get(i.id);if(w(a,"No init buffer for starting representation"),w(s,"No segments for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,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(o=>({...o,status:ee.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.round(a)>=Math.round(o.time.from)&&Math.round(a)<=Math.round(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=Ri(i);this.segments.set(t.id,[...o])}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,D=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+D||p<=i+D;return(u===ee.NONE||u===ee.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!si(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==Ke.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===ee.NONE||l.status===ee.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ke.BYTE_RANGE:{s=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Ke.TEMPLATE:{const d=e.at(0);s=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:N(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await oe(c,async function*(){const d=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(s,{range:a,onProgress:(d,h)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,h,c)}catch(u){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:c,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(d)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&P(i)&&(t=He(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,s,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=u=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),u.segment.status=ee.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const l of this.representations.values())if(l.id!==t)for(const p of this.segments.get(l.id)??[])p.status===ee.FED&&p.time.from===u.segment.time.from&&p.time.to===u.segment.time.to&&(p.status=ee.NONE);this.activeSegments.delete(u),this.detectGapsWhenIdle(t,[u.segment])},c=this.representations.get(t);if(!c)return;const d=c.segmentReference.type,h=e.byteLength;for(const u of this.activeSegments){const{segment:l}=u,p=d===Ke.BYTE_RANGE,S=p?l.byte.to-l.byte.from+1:h;if(u.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const b=p?l.byte.from-i:0,D=p?l.byte.to-i:e.byteLength,C=b<s,m=D<=s;if(l.status===ee.DOWNLOADING&&C&&m){l.status=ee.DOWNLOADED,this.activeSegments.delete(u);const $=new DataView(e.buffer,e.byteOffset+b,S);this.sourceBufferTaskQueue.append($,a).then(x=>x&&!a.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&C&&(u.loadedBytes=Math.min(S,s-b),u.loadedBytes>u.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+b+u.feedingBytes,u.loadedBytes-u.feedingBytes),x=u.loadedBytes===S?$:this.containerParser.parseFeedableSegmentChunk($);x?.byteLength&&(l.status=ee.PARTIALLY_FED,u.feedingBytes+=x.byteLength,this.sourceBufferTaskQueue.append(x,a).then(H=>{if(a.aborted)n();else if(H)u.fedBytes+=x.byteLength,u.fedBytes===S&&o(u);else{if(u.feedingBytes<S)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.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,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Fi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:c,dataView:d,segments:h}=o,u=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,u),this.segments.set(e.id,this.isLive?Ri(h):h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h="size"in d?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===ee.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===ee.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===ee.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===ee.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!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 a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(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),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=ee.PARTIALLY_EJECTED:s.status=ee.NONE)}}};var Kt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Kt||(Kt={}));let un=class{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new et;subscription=new se;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}=fs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=It(t));const i=yield zt(t,{signal:this.abortAllController.signal}).catch(li);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Kt.HEADER:Kt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(i)switch(t){case Kt.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case Kt.PARAM:{const T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:N(t)}this.requestQuic&&(c=It(c));let h=this.abortAllController.signal,u;if(n){const T=new et;if(u=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{T.abort()}catch(V){li(V)}}),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(V){li(V)}h=T.signal}const l=ne(),p=yield zt(c,{priority:a,headers:d,signal:h}).catch(li),S=ne();if(this.throughputEstimator?.addRawRtt(S-l),!p)return u?.unsubscribe(),null;if(!p.ok||!p.body)return u?.unsubscribe(),Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const v=parseInt(p.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!v){const T=yield p.arrayBuffer();return this.throughputEstimator?.addRawSpeed(T.byteLength,ne()-S),s?.(new DataView(T),T.byteLength),u?.unsubscribe(),T}if(!s&&!o)return u?.unsubscribe(),p.arrayBuffer();const[b,D]=p.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(D);let m=0;const $=new ArrayBuffer(v),x=new Uint8Array($),H=new DataView($);let q=!1;const F=T=>{u?.unsubscribe(),q=!0,li(T)},G=oe(h,async function*({done:T,value:V}){if(m===0&&this.lastRequestFirstBytes$.next(ne()-l),h.aborted){u?.unsubscribe();return}!T&&V&&(x.set(V,m),m+=V.byteLength,s?.(H,m),yield C?.read().then(G,F))}.bind(this));return yield C?.read().then(G,F),u?.unsubscribe(),q?null:$}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ke.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ke.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ke.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const D=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!D)return null;v=new DataView(D)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==Ke.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(n=>({...n,status:ee.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))};const li=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},$s=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},es=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},hn=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=$s(l);else if(p){const m=$s(p);P(m)&&(u=m)}else v&&(u=parseInt(v,10));let b=0;const D=a.getAttribute("profiles")?.split(",")??[],C=D.includes(Oi.WEBM_AS_IN_FFMPEG)||D.includes(Oi.WEBM_AS_IN_SPEC)?ii.WEBM:ii.MP4;for(const m of o){const $=m.getAttribute("mimeType"),x=m.getAttribute("codecs"),H=m.getAttribute("contentType")??$?.split("/")[0],q=m.getAttribute("profiles")?.split(",")??[],F=m.querySelectorAll("Representation"),G=m.querySelector("SegmentTemplate");if(H===Re.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=m.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Re.TEXT].push({id:V,lang:z,isAuto:ke,kind:Re.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??$,z=T.getAttribute("codecs")??x??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=m.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,Ce=pe?ji(pe):void 0,dt=T.getAttribute("id")??(b++).toString(10),ci=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,Wt=`${dt}@${ci}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Fe=[...D,...q,...ye];let De;const Et=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(Et){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,ct]=Ae.split("-").map(Ge=>parseInt(Ge,10)),Ve={from:Pe,to:ct},it=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[Mt,kt]=it?it.split("-").map(Ge=>parseInt(Ge,10)):[],st=it?{from:Mt,to:kt}:void 0;De={type:Ke.BYTE_RANGE,url:we,initRange:Ve,indexRange:st}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),ct=Te.getAttribute("initialization")??"",Ve=Te.getAttribute("media"),it=parseInt(Te.getAttribute("startNumber")??"",10)??1,Mt=es(ct,Ae);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");const kt=Te.querySelectorAll("SegmentTimeline S")??[],st=[];let Ge=0;if(kt.length){let Ot=it,ze=0;for(const Nt of kt){const qe=parseInt(Nt.getAttribute("d")??"",10),ve=parseInt(Nt.getAttribute("r")??"",10)||0,rt=parseInt(Nt.getAttribute("t")??"",10);ze=Number.isFinite(rt)?rt:ze;const Ue=qe/Pe*1e3,ut=ze/Pe*1e3;for(let $t=0;$t<ve+1;$t++){const ui=es(Ve,{...Ae,segmentNumber:Ot.toString(10),segmentTime:(ze+$t*qe).toString(10)}),Di=(ut||0)+$t*Ue,Qt=Di+Ue;Ot++,st.push({time:{from:Di,to:Qt},url:ui})}ze+=(ve+1)*qe,Ge+=(ve+1)*Ue}}else if(P(u)){const ze=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,Nt=Math.ceil(u/ze);let qe=0;for(let ve=1;ve<Nt;ve++){const rt=es(Ve,{...Ae,segmentNumber:ve.toString(10),segmentTime:qe.toString(10)});st.push({time:{from:qe,to:qe+ze},url:rt}),qe+=ze}}De={type:Ke.TEMPLATE,baseUrl:we,initUrl:Mt,totalSegmentsDurationMs:Ge,segments:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ye={video:Re.VIDEO,audio:Re.AUDIO,text:Re.TEXT}[te];Ye&&s[Ye].push({id:Wt,kind:Ye,segmentReference:De,profiles:Fe,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:Ce,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},as=1e3,As=["timeupdate","progress","play","seeked","stalled","waiting"];var Je;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Je||(Je={}));let ln=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Je.NONE);currentVideoRepresentation$=new g(void 0);currentVideoRepresentationInit$=new g(void 0);error$=new I;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);isLive$=new g(!1);liveDuration$=new g(0);liveAvailabilityStartTime$=new g(void 0);bufferLength$=new g(0);liveLoadBufferLength$=new g(0);forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new et;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new un({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Me(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Je.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Je.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(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:L.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=hn(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Re.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,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){w(this.element),this.manifestUrlString=Me(this.manifestUrlString,e,fe.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=oe(this.destroyController.signal,async function*(e,t){w(this.manifest),w(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Je.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 ks(Re.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new ks(Re.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(Gt(as).subscribe(n=>{if(this.element?.paused){const o=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Me(this.manifestUrlString,o+1e3,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...As.map(n=>M(this.element,n))).pipe(Er(as),A(n=>this.element?He(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async o=>{w(this.element);const c=this.element.playbackRate,d=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),h=sn*c,u=an*c,l=rn*c;n=o>n?o:n;const p=d===0&&o<l,S=d!==0&&o<h+l&&o>=h,v=d!==0&&o<h;if(v||S){const b=n-(h+u),D=Math.trunc(d+b/c);let C;o?D>0?C=D:C=0:C=d,this.manifestUrlString=Me(this.manifestUrlString,C,fe.DASH_CMAF_OFFSET_P)}(p||v||S)&&(await this.updateLive(),n=0)}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,xe({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.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(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Je.REPRESENTATIOS_READY)}.bind(this));initBuffer(){w(this.element),this.state$.setState(Je.RUNNING),this.subscription.add(O(...As.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Re.VIDEO]:this.videoBufferManager,[Re.AUDIO]:this.audioBufferManager,[Re.TEXT]:null}[e]?.switchTo(t)}seek(e,t){w(this.element),w(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),si(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(Je.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=Gt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:L.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 a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.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 fn{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class pn{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,a=t-this.camera.orientation.y,n=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:a,z:n},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 mn=`#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;}`,gn=`#ifdef GL_ES
37
+ `}),T}return d?.recordSwitch(F),F};var Fe=r=>new URL(r).hostname;const Zr=300,ki=(r,e=Zr)=>new Qi(t=>{const{width:i,height:s}=r.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const a=new ResizeObserver(vr(n=>{const o=n[0];if(!o)return;let c,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,c=o.contentBoxSize[0].inlineSize):o.contentRect&&(c=o.contentRect.width,d=o.contentRect.height),P(c)&&P(d)&&t.next({width:c,height:d})},e));return a.observe(r),()=>a.disconnect()});class wi{onDroopedVideoFramesLimit$=new I;subscription=new se;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new I;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(M(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Gt(this.droppedFramesChecker.checkTime).pipe(K(()=>this.playing),K(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(je(this.droppedFramesChecker.checkTime)),i=O(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&&!Yt(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,a=1-(i-s)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&ei(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])=>Ci(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 hi={};var X;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(X||(X={}));const Ee=(r,e)=>new Qi(t=>{const i=s=>t.next(s);return r.on(e,i),()=>r.off(e,i)});class bs{subscription=new se;videoState=new de(X.DOWNLOADING_LIB);video;player;params;textTracksManager=new ot;droppedFramesManager=new wi;videoTracks$=new m([]);frameRatesByFrameHeight={};isLive$=new m(void 0);maxSeekBackTime$=new m(1/0);availableFrom$=new m(void 0);elementSize$=new m(void 0);liveOffset=new Ai;constructor(e){this.video=bt(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(Fe(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:x.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||(hi.MediaPlayer=s.MediaPlayer,hi.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){D(hi.MediaPlayer,"dashjs not loaded"),D(hi.Debug,"dashjs not loaded"),this.player=hi.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?ji(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Vr(this.player),Or(this.player),this.params.tuning.requestQuick&&Fr(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:x.WTF,message:"DashIFProvider internal logic error",thrown:g})},s=(g,E)=>this.subscription.add(g.subscribe(E,i));s(ki(this.video),this.elementSize$),s(Ee(this.player,"error").pipe(A(g=>{const E=typeof g.error=="object"?g.error.code:g.error,L=typeof g.error=="object"?g.error.message:void 0;return{id:`DashJS#${E}`,message:L}})),e.error$),s(Ee(this.player,"playbackError").pipe(A(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const a=Ee(this.player,"qualityChangeRendered").pipe(K(({mediaType:g})=>g==="video"),A(({newQuality:g})=>this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===g)?.track));a.pipe(K(P)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(K(({to:g})=>g===X.STREAM_INITIALIZED),be()).subscribe(()=>{this.subscription.add(nt(t.videoTrack,()=>{const g=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===g)?.track},g=>{if(Y(g))return;const E=this.videoTracks$.getValue().find(({track:L})=>L.id===g.id)?.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:a,onError:i}))},i)),this.subscription.add(nt(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,g=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:g}}}}),{onError:i})),s(Ee(this.player,"bufferStateChanged").pipe(K(({mediaType:g})=>g==="video"),A(({state:g})=>g==="bufferStalled")),e.isBuffering$),s(Ee(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:E}})=>{const L=this.player.getDashMetrics(),H=L.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),q=L.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type")??Ei.HTTP1,F={1:!0,0:!1}[H]??void 0;this.params.output.httpConnectionType$.next(q),this.params.output.httpConnectionReused$.next(F),e.hostname$.next(Fe(E))}),s(Ee(this.player,"streamInitialized"),({streamInfo:{duration:g,manifestInfo:{isDynamic:E,availableFrom:L}}})=>{this.isLive$.next(E),this.availableFrom$.next(L.getTime()),E||e.duration$.next(g);const H=[],q=this.player.getQualityFor("video");let F;for(const G of this.player.getBitrateInfoListFor("video")){const T=G.qualityIndex.toString(10),V=Ct(G),z=G.bitrate/1e3,te={width:G.width,height:G.height},ye=this.frameRatesByFrameHeight[G.height];if(V){const ke={id:T,quality:V,bitrate:z,size:te,fps:ye};H.push({track:ke,bitrateInfo:G}),G.qualityIndex===q&&(F=ke)}}this.videoTracks$.next(H),e.availableVideoTracks$.next(H.map(({track:G})=>G)),F&&e.currentVideoTrack$.next(F),this.videoState.setState(X.STREAM_INITIALIZED),this.videoState.startTransitionTo(X.READY)}),s(Ee(this.player,"fragmentLoadingCompleted"),({request:g})=>{if(!g.requestEndDate||!g.firstByteDate||!g.bytesLoaded)return;const E=g.requestEndDate.getTime()-g.firstByteDate.getTime(),L=g.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(L,E)}),s(O(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 g=this.params.dependencies.throughputEstimator.throughput$.getValue(),E=qt(this.videoTracks$.getValue().map(({track:q})=>q),{container:this.elementSize$.getValue(),throughput:g,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),L=t.autoVideoTrackLimits.getTransition();L&&e.autoVideoTrackLimits$.next(L.to);const H=this.videoTracks$.getValue().find(({track:q})=>q===E);H?.bitrateInfo&&this.player.setQualityFor("video",H?.bitrateInfo.qualityIndex,!1)}),s(Le({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(K(P))}).pipe(K(({isLive:g})=>g),A(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const n=Ee(this.player,"playbackTimeUpdated").pipe(A(({time:g})=>g??0));s(Le({availableFrom:this.availableFrom$.pipe(K(P)),currentTime:n}),({availableFrom:g,currentTime:E})=>this.params.output.liveTime$.next(g+E*1e3)),s(n.pipe(K(()=>this.isLive$.getValue()===!1)),e.position$),s(Ee(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(Ee(this.player,"playbackEnded"),e.endedEvent$),s(Ee(this.player,"playbackProgress").pipe(A(()=>zs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(Ee(this.player,"playbackPlaying"),()=>{this.videoState.setState(X.PLAYING),R(t.playbackState,f.PLAYING)}),s(Ee(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(Ee(this.player,"playbackPaused"),()=>{this.videoState.setState(X.PAUSED),R(t.playbackState,f.PAUSED)}),s(Ee(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===X.READY&&this.videoState.setState(X.READY)}),s(this.isLive$,e.isLive$),s(ki(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=Nr(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(be()),e.firstBytesEvent$),s(Ee(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(Le({isLive:this.isLive$,isShort:e.duration$.pipe(A(g=>g<60))}),({isLive:g,isShort:E})=>{const L=!g&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:L}}})}),s(n.pipe(K(g=>g>this.params.tuning.insufficientBufferRuleMargin),be()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Ee(this.player,"manifestLoaded").pipe(be()).subscribe(()=>{this.subscription.add(Ee(this.player,"playbackPlaying").pipe(be(),ti(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(Ee(this.player,"manifestLoaded"),g=>{if(g.data?.Period?.AdaptationSet){const E=[];for(const L of g.data?.Period?.AdaptationSet)if(L.contentType==="text"){const H=L.Representation?.id,q=new URL(L.Representation?.BaseURL,g.data?.baseUri).toString(),F="internal",G=L.lang;E.push({id:H,url:q,type:F,language:G})}t.internalTextTracks.startTransitionTo(E)}}),this.subscription.add(_t(this.video,t.isLooped,i));const{volumeState$:l,looped$:p,playbackRateState$:S,inPiP$:v,inFullscreen$:b,pause$:w,playing$:C}=Tt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:C,pause$:w,tracks$:this.videoTracks$.pipe(A(g=>g.map(({track:E})=>E)))}),this.subscription.add(St(this.video,t.volume,l,i)),this.subscription.add(l.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Dt(this.video,t.playbackRate,S,i)),this.subscription.add(v.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(X.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(X.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=Oe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,fe.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(X.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(X.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(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===X.DOWNLOADING_LIB||e===X.STREAM_INITIALIZED))switch(i?.to!==f.PAUSED&&s.state===j.Requested&&e!==X.STOPPED&&t!==f.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case f.STOPPED:{switch(e){case X.STOPPED:break;case X.PLAYING:case X.PAUSED:case X.READY:this.stop();break;default:N(e)}break}case f.READY:{switch(e){case X.STOPPED:this.prepare();break;case X.PLAYING:case X.PAUSED:case X.READY:break;default:N(e)}break}case f.PLAYING:{switch(e){case X.PLAYING:break;case X.PAUSED:a&&(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 X.READY:this.play();break;case X.STOPPED:this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case X.PLAYING:this.pause(),this.liveOffset.pause();break;case X.PAUSED:break;case X.READY:this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case X.STOPPED:this.prepare();break;default:N(e)}break}default:N(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}yt(this.video),this.params.output.element$.next(void 0)}}var oi=r=>{switch(r){case"mobile":return Je.Q_144P;case"lowest":return Je.Q_240P;case"low":return Je.Q_360P;case"sd":case"medium":return Je.Q_480P;case"hd":case"high":return Je.Q_720P;case"fullhd":case"full":return Je.Q_1080P;case"quadhd":case"quad":return Je.Q_1440P;case"ultrahd":case"ultra":return Je.Q_2160P}};const ys=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Pt=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!ys(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return ys(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function Me(){return ne()}function Ws(r){return Me()-r}function Ts(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,c=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return c&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ea(r,e,t){const i=(...s)=>{t.apply(null,s),r.removeEventListener(e,i)};r.addEventListener(e,i)}function _i(r,e,t,i){const s=window.XMLHttpRequest;let a,n,o,c=!1,d=0,h,u,l=!1,p="arraybuffer",S=7e3,v=2e3,b=()=>{if(c)return;D(h);const z=Ws(h);let te;if(z<v){te=v-z,setTimeout(b,te);return}v*=2,v>S&&(v=S),n&&n.abort(),n=new s,H()};const w=z=>(a=z,V),C=z=>(u=z,V),g=()=>(p="json",V),E=()=>{if(!c){if(--d>=0){b(),i&&i();return}c=!0,u&&u(),t&&t()}},L=z=>(l=z,V),H=()=>{h=Me(),n=new s,n.open("get",r);let z=0,te,ye=0;const ke=()=>(D(h),Math.max(h,Math.max(te||0,ye||0)));if(a&&n.addEventListener("progress",U=>{const re=Me();a.updateChunk&&U.loaded>z&&(a.updateChunk(ke(),U.loaded-z),z=U.loaded,te=re)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(c)return;D(n);const U=n.status;if(U>=200&&U<300){if(n.response.byteLength&&a){const re=n.response.byteLength-z;re&&a.updateChunk&&a.updateChunk(ke(),re)}u&&u(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),l){const U=()=>{D(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=Me(),n.removeEventListener("readystatechange",U))};n.addEventListener("readystatechange",U)}return n.responseType=p,n.send(),V},V={withBitrateReporting:w,withParallel:L,withJSONResponse:g,withRetryCount:z=>(d=z,V),withRetryInterval:(z,te)=>(P(z)&&(v=z),P(te)&&(S=te),V),withTimeout:z=>(o=z,V),withFinally:C,send:H,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return V}const ta=100,ia=2e3,sa=500;let ra=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-sa;if(t-e>ia){let i=0,s=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,s+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const c=a.bytes*n/o;s+=c,a.start=t,a.bytes-=c}}}if(s>0&&i>0){const a=s*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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>ta&&(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 aa{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}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=Me(),s=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=c=>{e._complete=1,e._responseData=c,e._downloadTime=Me()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=_i(t,a,()=>s("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Me()}_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=Me();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 a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}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 xi=1e4,Ri=3,na=300,oa=2e3,da=6e4,ca=10,ua=1,ha=500;class la{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 ra(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ts(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=Ts(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,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||P(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:a}=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 n=()=>{ea(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new aa(Ri,xi,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 a=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const E=a&&(!h||h===this.rep);return E||t("Not running!"),E},l=(E,L,H)=>{c&&c.abort(),c=_i(this.urlResolver.resolve(E,!1),L,H,()=>this._retryCallback()).withTimeout(xi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ri).withFinally(()=>{c=null}).send()},p=(E,L,H)=>{D(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),L,H,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=E=>{const L=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${L}=>${E}`),i.playbackRate=E)},v=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const H=Me()-1e4;let q=0;for(let G=0;G<this.bufferStates.length;G++){const T=this.bufferStates[G];E=Math.min(E,T.buf),T.ts<H&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${E} drop=${q} jitter=${this.sourceJitter}`);let F=E-ua;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?S(1.15):F>1?S(1.1):F>.3?S(1.05):S(1)}},w=E=>{let L;const H=()=>L&&L.start?L.start.length:0,q=U=>L.start[U]/1e3,F=U=>L.dur[U]/1e3,G=U=>L.fragIndex+U,T=(U,re)=>({chunkIdx:G(U),startTS:q(U),dur:F(U),discontinuity:re}),V=()=>{let U=0;if(L&&L.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,pe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,$e=re;this.sourceJitter>1&&($e+=this.sourceJitter-1);let _e=L.dur.length-1;for(;_e>=0&&($e-=L.dur[_e],!($e<=0));--_e);U=Math.min(_e,L.dur.length-1-pe),U=Math.max(U,0)}return T(U,!0)},z=U=>{const re=H();if(!(re<=0)){if(P(U)){for(let pe=0;pe<re;pe++)if(q(pe)>U)return T(pe)}return V()}},te=U=>{const re=H(),pe=U?U.chunkIdx+1:0,$e=pe-L.fragIndex;if(!(re<=0)){if(!U||$e<0||$e-re>ca)return t(`Resync: offset=${$e} bChunks=${re} chunk=`+JSON.stringify(U)),V();if(!($e>=re))return T(pe-L.fragIndex,!1)}},ye=(U,re,pe)=>{d&&d.abort(),d=_i(this.urlResolver.resolve(U,!0,this.lowLatency),re,pe,()=>this._retryCallback()).withTimeout(xi).withRetryCount(Ri).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(U,re)=>{ye(E,pe=>{if(!u())return;L=pe;const $e=!!L.lowLatency;$e!==this.lowLatency&&v($e);let _e=0;for(let dt=0;dt<L.dur.length;++dt)_e+=L.dur[dt];_e>0&&(D(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(_e/L.dur.length)),s({name:"index",zeroTime:L.zeroTime,shiftDuration:L.shiftDuration}),this.sourceJitter=L.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,L.jitter/1e3)):1,U(z(re))},()=>this._handleNetworkError())},nextChunk:te}},C=()=>{a=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),D(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:E=>{const{videoElement:L,logger:H}=this.params;let q=w(e.jidxUrl),F,G,T,V,z=0,te,ye,ke;const U=()=>{te&&(clearTimeout(te),te=void 0);const ae=Math.max(ha,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=z+ae,Ve=Me(),De=Math.min(1e4,we-Ve);z=Ve;const Et=()=>{d||u()&&q.seek(()=>{u()&&(z=Me(),re(),U())})};De>0?te=window.setTimeout(()=>{this.paused?U():Et()},De):Et()},re=()=>{let ae;for(;ae=q.nextChunk(V);)V=ae,ci(ae);const we=q.nextChunk(T);if(we){if(T&&we.discontinuity){H("Detected discontinuity; restarting playback"),this.paused?U():(C(),this._initPlayerWith(e));return}dt(we)}else U()},pe=(ae,we)=>{if(!u()||!this.sourceBuffer)return;let Ve,De,Et;const Te=Ge=>{window.setTimeout(()=>{u()&&pe(ae,we)},Ge)};if(this.sourceBuffer.updating)H("Source buffer is updating; delaying appendBuffer"),Te(100);else{const Ge=Me(),Ae=L.currentTime;!this.paused&&L.buffered.length>1&&ye===Ae&&Ge-ke>500&&(H("Stall suspected; trying to fix"),this._fixupStall()),ye!==Ae&&(ye=Ae,ke=Ge);const Pe=this._getBufferSizeSec();if(Pe>30)H(`Buffered ${Pe} seconds; delaying appendBuffer`),Te(2e3);else try{this.sourceBuffer.appendBuffer(ae),this.videoPlayStarted?(this.bufferStates.push({ts:Ge,buf:Pe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(ct){if(ct.name==="QuotaExceededError")H("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(Ve=this.sourceBuffer.buffered.start(0),De=Ae,De-Ve>4&&this.sourceBuffer.remove(Ve,De-3)),Te(1e3);else throw ct}}},$e=()=>{G&&F&&(H([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(T)]),pe(G,function(){G=null,re()}))},_e=ae=>e.fragUrlTemplate.replace("%%id%%",ae.chunkIdx),dt=ae=>{u()&&p(_e(ae),(we,Ve)=>{if(u()){if(Ve/=1e3,G=we,T=ae,n=ae.startTS,Ve){const De=Math.min(10,ae.dur/Ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}$e()}},()=>this._handleNetworkError())},ci=ae=>{u()&&(D(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(_e(ae),!1)))},Wt=ae=>{u()&&(e.cachedHeader=ae,pe(ae,()=>{F=!0,$e()}))};a=!0,q.seek(ae=>{if(u()){if(z=Me(),!ae){U();return}V=ae,!Y(E)||ae.startTS>E?dt(ae):(T=ae,re())}},E),e.cachedHeader?Wt(e.cachedHeader):l(e.headerUrl,Wt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),P(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,D(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return P(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let l,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(p=this._getBufferSizeSec(),S=u/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}l=this._selectQuality(u),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${u}`)},a=(()=>({updateChunk:(l,p)=>{const S=Me();if(this.chunkRateEstimator.addInterval(l,S,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-l,speed:b}),!0}},get:()=>{const l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=a.get();if(u&&o&&this.autoQuality){if(c&&u>o&&Ws(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,l)=>{const p=a.updateChunk(u,l);return p&&d(),p},notifySwitch:u=>{const l=Me();u<o&&(n=l),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=_i(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(xi).withRetryCount(Ri).withRetryInterval(na,oa).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Pt(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,a=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&s.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=d,o.push(c))}),o.sort(function(c,d){return c.video&&d.video?d.video.height-c.video.height:d.bitrate-c.bitrate}),o):(i({name:"error",type:"partial_metadata"}),[])};this.manifest=a(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))},da))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var J;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(J||(J={}));const fa=[J.PAUSED,J.PLAYING,J.READY],pa=[J.PAUSED,J.PLAYING,J.READY];class ma{subscription=new se;video;videoState=new de(J.STOPPED);dash;representations$=new m([]);textTracksManager=new ot;droppedFramesManager=new wi;maxSeekBackTime$=new m(1/0);zeroTime$=new m(void 0);liveOffset=new Ai;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:x.WTF,message:"DashLiveProvider internal logic error",thrown:s})};O(this.videoState.stateChangeStarted$.pipe(A(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(s)}`})}),this.video=bt(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(Fe(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=Tt(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(A(s=>s.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(J.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(le(),A(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(Le({zeroTime:this.zeroTime$.pipe(K(P)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:a})=>this.params.output.liveTime$.next(s+a*1e3),t)).add(_t(this.video,this.params.desiredState.isLooped,t)).add(St(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Dt(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 a=s&&Er(s);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case J.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(f.STOPPED);break;case J.MANIFEST_READY:case J.READY:this.params.desiredState.playbackState.getTransition()?.to===f.READY&&this.params.desiredState.playbackState.setState(f.READY);break;case J.PAUSED:this.params.desiredState.playbackState.setState(f.PAUSED);break;case J.PLAYING:this.params.desiredState.playbackState.setState(f.PLAYING);break;default:return N(s.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ne(["init"])).pipe(je(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),yt(this.video)}createLiveDashPlayer(){const e=new la({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&&P(t)?t:qt(e.map(({track:d})=>d),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=s?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(n||a!==o)&&this.setVideoTrack(s),c&&this.setAutoQuality(i),n||c||a!==o){const d=e.find(({track:h})=>h.id===a)?.representation;D(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;D(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===f.PAUSED&&i===J.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Oe(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,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:x.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const a=s.name??s.index.toString(10),n=oi(s.name)??Ct(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:a,quality:n,bitrate:o,size:c};i.push({track:d,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===J.MANIFEST_READY&&this.videoState.setState(J.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),P(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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(J.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(pa.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==f.PAUSED&&a.state===j.Requested&&fa.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_READY),this.dash.attachSource(Oe(this.params.source.url));return;case J.MANIFEST_READY:this.videoState.startTransitionTo(J.READY),this.prepare();break;case J.READY:if(i===f.PAUSED)this.videoState.setState(J.PAUSED);else if(i===f.PLAYING){this.videoState.startTransitionTo(J.PLAYING);const c=s?.from;c&&c===f.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(J.PAUSED)})}return;case J.PLAYING:i===f.PAUSED&&(this.videoState.startTransitionTo(J.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case J.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(J.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(J.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Oe(this.params.source.url,c))}return;default:return N(e)}}}var fs=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?Ei.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},Ye=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){const s=r.start(i)*1e3,a=r.end(i)*1e3;s<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const ga=r=>{const e=document.createElement("a");return e.href=r,e.origin},Sa=r=>{const e=document.createElement("a");return e.href=r,e.host};class Qs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,a,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=n,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(Sa(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 Mi{_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 a=0;for(let n=0,o=s.length;n<o;n++)a+=s.end(n)-s.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,a,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,l=0;const p=v=>{s(Mi._str2ua(v.substr(c))),c=v.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=It(S)),this._lastXhr=new Qs(S,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const b=Date.now()-d;this._params.onBandwidthChange({size:v.length,duration:b,speed:8*v.length/(b/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),a?.()},v=>{if(v.length-c>o&&p(v),u===0){u=Date.now();return}l=v.length-h;const b=Date.now()-u;l>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:l,duration:b,speed:8*l/(b/1e3)}),l=0,h=v.length,u=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},n,(v,b,w)=>this._params.onError(v,b,w))})}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=Mi._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 ba{_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=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},s=t.exec(e),a=s?.[1]==="-"?-1:1,n={years:i(s?.[2],a),months:i(s?.[3],a),weeks:i(s?.[4],a),days:i(s?.[5],a),hours:i(s?.[6],a),minutes:i(s?.[7],a),seconds:i(s?.[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=It(i)),new Qs(i,t,s=>{this.attachManifest(s,t,ga(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,a,n)=>this._params.onError(s,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,h)=>{const u=d.attributes.getNamedItem(h);return u?u.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),l=h&&h.getElementsByTagName("Initialization")[0],p=l&&n(l,"range").split("-");if(!p||!u){const g=d.parentElement;if(g?.getAttribute("contentType")==="text"){const E=d.getAttribute("id")??void 0,L=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,H=g.getAttribute("lang")??void 0;L&&c.push({id:E,url:L,language:H})}return}const S=.1,v=Number(d.attributes.getNamedItem("bandwidth")?.value),b=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let w;const C=d.attributes.getNamedItem("frameRate")?.value??void 0;w=C?ji(C):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:v,baseURL:b,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:w,bufferSize:S*v/8,bufferLength:S,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:h,url:u})=>{const l=document.createElement("track");u&&l.setAttribute("src",u),d&&l.setAttribute("id",d),h&&l.setAttribute("srclang",h),this._video.appendChild(l)}),this._representations.sort((d,h)=>h.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:c})}_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 a=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,a);const n=new DataView(s.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let c=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const h=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let l=0;l<h;l+=1){const p=d+(n.getUint32(a,!1)&2147483647),S=c+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:c/o,toTime:S/o,fromOffset:d,toOffset:p-1}),d=p,c=S}const u=e.refs[e.refs.length-1];u.toTime-u.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,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||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(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}u=p.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},u*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},c=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Mi({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",c),i.removeEventListener("webkitsourceopen",c)};i.addEventListener("sourceopen",c,!1),i.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-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 a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),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 a=.1;if(s.toTime<i.to+a){const n=this._findRef(s.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,n.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,(o,c)=>this._stream.remove(o,c)),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||Y(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 a=t[s];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!i||a.fromTime<i.fromTime)&&(i=a)}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 Z;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Z||(Z={}));const ya=[Z.PAUSED,Z.PLAYING];class Ta{videoState=new de(Z.STOPPED);subscription=new se;video;buffer;dash;representations$=new m([]);currentRepresentation$=new m(void 0);params;textTracksManager=new ot;droppedFramesManager=new wi;elementSize$=new m(void 0);dashLiteEvents={idxRequestPing$:new I,responseHeaders$:new I,manifestReady$:new I,representationPlay$:new I,error$:new I};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),O(this.videoState.stateChangeStarted$.pipe(A(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=bt(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(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new qr(this.video),this.dash=new ba({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:x.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=o=>{e.error$.next({id:"DashProvider",category:x.WTF,message:"DashProvider internal logic error",thrown:o})},s=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},a=Tt(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{Y(this.params.desiredState.seekState.getState().state!==j.Applying)&&(this.videoState.getState()===Z.PLAYING||this.videoState.getState()===Z.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(St(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dt(this.video,t.playbackRate,a.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$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(A(o=>o.map(({track:c})=>c)))}),n(ki(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Z.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(A(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:x.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(O(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$,M(this.video,"progress")).pipe(A(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState()?.id,u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),p=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let S;if(!p&&P(h))S=h;else{const v=Ye(this.video.buffered,this.video.currentTime*1e3),b=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(v/b,1);S=qt(c.map(({track:g})=>g),{container:l,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:c.find(({representation:g})=>g===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const C=t.autoVideoTrackLimits.getTransition();C&&e.autoVideoTrackLimits$.next(C.to)}return P(S)?c.find(({track:v})=>v.id===S)?.representation:void 0}),le()).subscribe(this.currentRepresentation$,i)).add(Le({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(K(o=>o.to===Z.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(K(P))}).pipe(be()).subscribe(()=>this.videoState.setState(Z.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(K(P),le((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=Ye(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!s())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Fe(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=fs(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(be(),ti(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(K(P)).subscribe(this.handleRepresentationPlay,i)).add(O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(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),yt(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 N(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const a=s.name??s.id??s.height.toString(10),n=(s.name&&oi(s.name))??Ct(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:a,quality:n,bitrate:o,size:c,fps:d};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 a of t){const n=a.id||`${a.language}_${Date.now()}`;s.push({id:n,type:"internal",url:a.url||"",language:a.language,isAuto:a.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(Z.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 D(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(){Pt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.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(Z.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(!t)switch(s?.to!==f.PAUSED&&a.state===j.Requested&&ya.includes(e)&&this.seek(a.position,a.forcePrecise),e){case Z.STOPPED:this.videoState.startTransitionTo(Z.MANIFEST_LOADED),this.prepare();return;case Z.MANIFEST_LOADED:this.videoState.startTransitionTo(Z.INITIAL_REPRESENTATION_SELECTED);return;case Z.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Z.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Z.METADATA_LOADED:this.videoState.startTransitionTo(Z.READY),this.dash.updateRefsForCurrentTime();return;case Z.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Z.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}var Ie;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Ie||(Ie={}));var Oi;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Oi||(Oi={}));var Ze;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Ze||(Ze={}));var ee;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(ee||(ee={}));var ii;(function(r){r.MP4="mp4",r.WEBM="webm"})(ii||(ii={}));var Ni;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Ni||(Ni={}));var me;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(me||(me={}));class vs{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,a=i.length;s<a;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,a=i.length;s<a;s++){const n=i[s];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class js extends vs{constructor(){super(),this.listeners||vs.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 Js=class{constructor(){Object.defineProperty(this,"signal",{value:new js,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&&(Js.prototype[Symbol.toStringTag]="AbortController",js.prototype[Symbol.toStringTag]="AbortSignal");function Xs(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function va(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=r;if(!Xs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||s)&&(a=function(d,h){let u;h&&h.signal&&(u=h.signal,delete h.signal);const l=new t(d,h);return u&&Object.defineProperty(l,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),l},a.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const h=a&&a.prototype.isPrototypeOf(c)?c.signal:d?d.signal:void 0;if(h){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(h.aborted)return Promise.reject(u);const l=new Promise((p,S)=>{h.addEventListener("abort",()=>S(u),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([l,n(c,d)])}return n(c,d)},Request:a}}const Ji=Xs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ks=Ji?va({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,zt=Ji?Ks.fetch:window.fetch;Ji?Ks.Request:window.Request;const tt=Ji?Js:window.AbortController;var si=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const Ea=(r,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-s-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},ka=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Fi=ka?Ea:window.requestIdleCallback,$a=16;let Zs=!1;try{Zs=Wi().browser===us.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=$a}catch(r){console.error(r)}let Aa=class{bufferFull$=new I;error$=new I;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 a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Zs&&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:x.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:x.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:N(t)}}};var Vi=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};let vt=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}},er=class extends vt{},wa=class extends vt{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}}},Da=class extends vt{parseChildrenBoxes(){return di(this.content)}},Pa=class extends vt{data;constructor(e){super(e),this.data=this.content}},Di=class extends vt{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},La=class extends Di{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,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}},xa=class extends vt{parseChildrenBoxes(){return di(this.content)}},Ra=class extends vt{parseChildrenBoxes(){return di(this.content)}};var Ut;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ut||(Ut={}));let Ia=class extends Di{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ut.MONOSCOPIC;break;case 1:this.stereoMode=Ut.TOP_BOTTOM;break;case 2:this.stereoMode=Ut.LEFT_RIGHT;break;case 3:this.stereoMode=Ut.STEREO_CUSTOM;break;case 4:this.stereoMode=Ut.RIGHT_LEFT;break}this.cursor+=1}},Ca=class extends Di{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},_a=class extends Di{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},Ba=class extends vt{parseChildrenBoxes(){return di(this.content)}},Ma=class extends Di{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()}},Oa=class extends vt{parseChildrenBoxes(){return di(this.content)}},Na=class extends vt{parseChildrenBoxes(){return di(this.content)}};const Fa={ftyp:wa,moov:Da,mdat:Pa,sidx:La,trak:xa,mdia:Ba,tkhd:Ma,minf:Oa,sv3d:Ra,st3d:Ia,prhd:Ca,proj:Na,equi:_a,unknown:er};let Va=class{createBox(e,t){const i=Fa[e];return i?new i(t):new er(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Xi.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Xi=new Va;function gi(r,e){const t=new TextDecoder("ascii");let i=r.byteOffset,s=[];for(;i<r.byteLength;){const a=t.decode(new DataView(r.buffer,i,1));if(a===e[s.length]?s.push(a):s=[],s.length===4&&s.join("")===e){const o=new DataView(r.buffer,i-7,4).getUint32(0);return i-7+o>r.byteLength?null:Xi.createBox(e,new DataView(r.buffer,i-7))}i++}return null}function Ua(r,e){const t=[];let i=0;for(;i<r.byteLength;){const s=gi(new DataView(r.buffer,r.byteOffset+i,r.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function di(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Xi.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Ha=new TextDecoder("ascii"),Ya=r=>Ha.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Ga=r=>{const e=Xi.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:ee.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},za=r=>{const e=Ua(r,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(r.buffer,r.byteOffset,t)}return null},qa=r=>{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(gi(r,"sv3d")){e.is3dVideo=!0;const i=gi(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=gi(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=gi(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Wa={validateData:Ya,parseInit:qa,getIndexRange:()=>{},parseSegments:Ga,parseFeedableSegmentChunk:za};var k;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(k||(k={}));var _;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(_||(_={}));const Es={[k.EBML]:{type:_.Master},[k.EBMLVersion]:{type:_.UnsignedInteger},[k.EBMLReadVersion]:{type:_.UnsignedInteger},[k.EBMLMaxIDLength]:{type:_.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[k.DocType]:{type:_.String},[k.DocTypeVersion]:{type:_.UnsignedInteger},[k.DocTypeReadVersion]:{type:_.UnsignedInteger},[k.Void]:{type:_.Binary},[k.Segment]:{type:_.Master},[k.SeekHead]:{type:_.Master},[k.Seek]:{type:_.Master},[k.SeekID]:{type:_.Binary},[k.SeekPosition]:{type:_.UnsignedInteger},[k.Info]:{type:_.Master},[k.TimestampScale]:{type:_.UnsignedInteger},[k.Duration]:{type:_.Float},[k.Tracks]:{type:_.Master},[k.TrackEntry]:{type:_.Master},[k.Video]:{type:_.Master},[k.Projection]:{type:_.Master},[k.ProjectionType]:{type:_.UnsignedInteger},[k.ProjectionPrivate]:{type:_.Master},[k.Chapters]:{type:_.Master},[k.Cluster]:{type:_.Master},[k.Timestamp]:{type:_.UnsignedInteger},[k.SilentTracks]:{type:_.Master},[k.SilentTrackNumber]:{type:_.UnsignedInteger},[k.Position]:{type:_.UnsignedInteger},[k.PrevSize]:{type:_.UnsignedInteger},[k.SimpleBlock]:{type:_.Binary},[k.BlockGroup]:{type:_.Master},[k.EncryptedBlock]:{type:_.Binary},[k.Attachments]:{type:_.Master},[k.Tags]:{type:_.Master},[k.Cues]:{type:_.Master},[k.CuePoint]:{type:_.Master},[k.CueTime]:{type:_.UnsignedInteger},[k.CueTrackPositions]:{type:_.Master},[k.CueTrack]:{type:_.UnsignedInteger},[k.CueClusterPosition]:{type:_.UnsignedInteger},[k.CueRelativePosition]:{type:_.UnsignedInteger},[k.CueDuration]:{type:_.UnsignedInteger},[k.CueBlockNumber]:{type:_.UnsignedInteger},[k.CueCodecState]:{type:_.UnsignedInteger},[k.CueReference]:{type:_.Master},[k.CueRefTime]:{type:_.UnsignedInteger}},tr=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ui(r,t),s=i in Es,a=s?Es[i].type:_.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Ui(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Ui=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},pt=(r,e)=>{switch(e){case _.SignedInteger:return r.getInt8(0);case _.UnsignedInteger:return Ui(r);case _.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(r);case _.UTF8:return new TextDecoder("utf-8").decode(r);case _.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case _.Master:return r;case _.Binary:return r;default:N(e)}},ri=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=tr(i);if(!e(s))return;s.type===_.Master&&ri(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},Qa=r=>{if(r.getUint32(0)!==k.EBML)return!1;let e,t,i;const s=tr(r);return ri(s.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=pt(o,n):a===k.DocType?t=pt(o,n):a===k.DocTypeReadVersion&&(i=pt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},ir=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],ja=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],Ja=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ri(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===k.SeekID){const b=pt(S,p);d=Ui(b)}else l!==k.SeekPosition&&(d=void 0);return l===k.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===k.Info?a=!0:l===k.SeekHead?n=!0:l===k.TimestampScale?i=pt(S,p):l===k.Duration?s=pt(S,p):l===k.SeekPosition&&d===k.Cues?c=pt(S,p):l===k.Tracks?ri(S,({tag:b,type:w,value:C})=>b===k.ProjectionType?(h=pt(C,w)===1,!1):!0):a&&n&&ir.includes(l)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(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:c,is3dVideo:h,stereoMode:u,projectionType:Ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Xa=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ka=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ri(r,({tag:o,type:c,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&s(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=pt(d,c));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=pt(d,c));break;default:t&&ir.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:ee.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Za=r=>{let e=0,t=!1;try{ri(r,i=>i.tag===k.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ja.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},en={validateData:Qa,parseInit:Ja,getIndexRange:Xa,parseSegments:Ka,parseFeedableSegmentChunk:Za},sr=1e4,tn=3e4,sn=5e3,rn=sr,an=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?oi(a):void 0)??Ct({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},nn=({id:r,bitrate:e})=>({id:r,bitrate:e}),on=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},dn=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),Ii=r=>{const e=[];let t=0,i=r.length-1;for(;t<sr&&i>=0;)e.unshift(r[i]),t+=r[i].time.to-r[i].time.from,i--;return e};let ks=class{onLastSegment$=new m(!1);fullyBuffered$=new m(!1);playingRepresentation$=new m(void 0);playingRepresentationInit$=new m(void 0);error$=new I;gaps=[];isSeekingLive=!1;subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new tt;destroyAbortController=new tt;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,s,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1,manifest:d}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!d?.dynamic,this.container=i,i){case ii.MP4:this.containerParser=Wa;break;case ii.WEBM:this.containerParser=en;break;default:N(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=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);D(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Aa(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:x.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Vi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);D(i,"No init buffer for starting representation"),D(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(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);D(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),D(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 a=this.getCurrentPosition();P(a)&&(this.searchGaps(i,t),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Ye(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Vi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Ye(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===ee.FED&&!o.length&&Ye(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}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;P(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=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d)return;const h=Ii(d.segmentReference.segments);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);D(i);const s=Ii(i.segmentReference.segments),a=this.initData.get(i.id);if(D(a,"No init buffer for starting representation"),D(s,"No segments for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,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(o=>({...o,status:ee.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.round(a)>=Math.round(o.time.from)&&Math.round(a)<=Math.round(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=Ii(i);this.segments.set(t.id,[...o])}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,w=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+w||p<=i+w;return(u===ee.NONE||u===ee.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!si(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==Ze.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===ee.NONE||l.status===ee.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ze.BYTE_RANGE:{s=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Ze.TEMPLATE:{const d=e.at(0);s=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:N(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await oe(c,async function*(){const d=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(s,{range:a,onProgress:(d,h)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,h,c)}catch(u){this.error$.next({id:"SegmentFeeding",category:x.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:c,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(d)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&P(i)&&(t=Ye(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:x.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,s,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=u=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),u.segment.status=ee.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const l of this.representations.values())if(l.id!==t)for(const p of this.segments.get(l.id)??[])p.status===ee.FED&&p.time.from===u.segment.time.from&&p.time.to===u.segment.time.to&&(p.status=ee.NONE);this.activeSegments.delete(u),this.detectGapsWhenIdle(t,[u.segment])},c=this.representations.get(t);if(!c)return;const d=c.segmentReference.type,h=e.byteLength;for(const u of this.activeSegments){const{segment:l}=u,p=d===Ze.BYTE_RANGE,S=p?l.byte.to-l.byte.from+1:h;if(u.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const b=p?l.byte.from-i:0,w=p?l.byte.to-i:e.byteLength,C=b<s,g=w<=s;if(l.status===ee.DOWNLOADING&&C&&g){l.status=ee.DOWNLOADED,this.activeSegments.delete(u);const E=new DataView(e.buffer,e.byteOffset+b,S);this.sourceBufferTaskQueue.append(E,a).then(L=>L&&!a.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&C&&(u.loadedBytes=Math.min(S,s-b),u.loadedBytes>u.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+u.feedingBytes,u.loadedBytes-u.feedingBytes),L=u.loadedBytes===S?E:this.containerParser.parseFeedableSegmentChunk(E);L?.byteLength&&(l.status=ee.PARTIALLY_FED,u.feedingBytes+=L.byteLength,this.sourceBufferTaskQueue.append(L,a).then(H=>{if(a.aborted)n();else if(H)u.fedBytes+=L.byteLength,u.fedBytes===S&&o(u);else{if(u.feedingBytes<S)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.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,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Fi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:c,dataView:d,segments:h}=o,u=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,u),this.segments.set(e.id,this.isLive?Ii(h):h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h="size"in d?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===ee.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===ee.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===ee.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===ee.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!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 a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:x.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(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),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=ee.PARTIALLY_EJECTED:s.status=ee.NONE)}}};var Kt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Kt||(Kt={}));let cn=class{throughputEstimator;requestQuic;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);abortAllController=new tt;subscription=new se;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}=fs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=It(t));const i=yield zt(t,{signal:this.abortAllController.signal}).catch(li);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Kt.HEADER:Kt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(i)switch(t){case Kt.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case Kt.PARAM:{const T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:N(t)}this.requestQuic&&(c=It(c));let h=this.abortAllController.signal,u;if(n){const T=new tt;if(u=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{T.abort()}catch(V){li(V)}}),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(V){li(V)}h=T.signal}const l=ne(),p=yield zt(c,{priority:a,headers:d,signal:h}).catch(li),S=ne();if(this.throughputEstimator?.addRawRtt(S-l),!p)return u?.unsubscribe(),null;if(!p.ok||!p.body)return u?.unsubscribe(),Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const v=parseInt(p.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!v){const T=yield p.arrayBuffer();return this.throughputEstimator?.addRawSpeed(T.byteLength,ne()-S),s?.(new DataView(T),T.byteLength),u?.unsubscribe(),T}if(!s&&!o)return u?.unsubscribe(),p.arrayBuffer();const[b,w]=p.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(w);let g=0;const E=new ArrayBuffer(v),L=new Uint8Array(E),H=new DataView(E);let q=!1;const F=T=>{u?.unsubscribe(),q=!0,li(T)},G=oe(h,async function*({done:T,value:V}){if(g===0&&this.lastRequestFirstBytes$.next(ne()-l),h.aborted){u?.unsubscribe();return}!T&&V&&(L.set(V,g),g+=V.byteLength,s?.(H,g),yield C?.read().then(G,F))}.bind(this));return yield C?.read().then(G,F),u?.unsubscribe(),q?null:E}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ze.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ze.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ze.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const w=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!w)return null;v=new DataView(w)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==Ze.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(n=>({...n,status:ee.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))};const li=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},$s=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},es=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},un=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=$s(l);else if(p){const g=$s(p);P(g)&&(u=g)}else v&&(u=parseInt(v,10));let b=0;const w=a.getAttribute("profiles")?.split(",")??[],C=w.includes(Oi.WEBM_AS_IN_FFMPEG)||w.includes(Oi.WEBM_AS_IN_SPEC)?ii.WEBM:ii.MP4;for(const g of o){const E=g.getAttribute("mimeType"),L=g.getAttribute("codecs"),H=g.getAttribute("contentType")??E?.split("/")[0],q=g.getAttribute("profiles")?.split(",")??[],F=g.querySelectorAll("Representation"),G=g.querySelector("SegmentTemplate");if(H===Ie.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=g.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Ie.TEXT].push({id:V,lang:z,isAuto:ke,kind:Ie.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??E,z=T.getAttribute("codecs")??L??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=g.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,_e=pe?ji(pe):void 0,dt=T.getAttribute("id")??(b++).toString(10),ci=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,Wt=`${dt}@${ci}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Ve=[...w,...q,...ye];let De;const Et=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(Et){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,ct]=Ae.split("-").map(ze=>parseInt(ze,10)),Ue={from:Pe,to:ct},st=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[Mt,kt]=st?st.split("-").map(ze=>parseInt(ze,10)):[],rt=st?{from:Mt,to:kt}:void 0;De={type:Ze.BYTE_RANGE,url:we,initRange:Ue,indexRange:rt}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),ct=Te.getAttribute("initialization")??"",Ue=Te.getAttribute("media"),st=parseInt(Te.getAttribute("startNumber")??"",10)??1,Mt=es(ct,Ae);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const kt=Te.querySelectorAll("SegmentTimeline S")??[],rt=[];let ze=0;if(kt.length){let Ot=st,qe=0;for(const Nt of kt){const We=parseInt(Nt.getAttribute("d")??"",10),ve=parseInt(Nt.getAttribute("r")??"",10)||0,at=parseInt(Nt.getAttribute("t")??"",10);qe=Number.isFinite(at)?at:qe;const He=We/Pe*1e3,ut=qe/Pe*1e3;for(let $t=0;$t<ve+1;$t++){const ui=es(Ue,{...Ae,segmentNumber:Ot.toString(10),segmentTime:(qe+$t*We).toString(10)}),Pi=(ut||0)+$t*He,Qt=Pi+He;Ot++,rt.push({time:{from:Pi,to:Qt},url:ui})}qe+=(ve+1)*We,ze+=(ve+1)*He}}else if(P(u)){const qe=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,Nt=Math.ceil(u/qe);let We=0;for(let ve=1;ve<Nt;ve++){const at=es(Ue,{...Ae,segmentNumber:ve.toString(10),segmentTime:We.toString(10)});rt.push({time:{from:We,to:We+qe},url:at}),We+=qe}}De={type:Ze.TEMPLATE,baseUrl:we,initUrl:Mt,totalSegmentsDurationMs:ze,segments:rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ge={video:Ie.VIDEO,audio:Ie.AUDIO,text:Ie.TEXT}[te];Ge&&s[Ge].push({id:Wt,kind:Ge,segmentReference:De,profiles:Ve,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:_e,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},as=1e3,As=["timeupdate","progress","play","seeked","stalled","waiting"];var Xe;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Xe||(Xe={}));let hn=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Xe.NONE);currentVideoRepresentation$=new m(void 0);currentVideoRepresentationInit$=new m(void 0);error$=new I;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);isLive$=new m(!1);liveDuration$=new m(0);liveAvailabilityStartTime$=new m(void 0);bufferLength$=new m(0);liveLoadBufferLength$=new m(0);forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new tt;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new cn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Oe(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Xe.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Xe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:x.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(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:x.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=un(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:x.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Ie.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,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){D(this.element),this.manifestUrlString=Oe(this.manifestUrlString,e,fe.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=oe(this.destroyController.signal,async function*(e,t){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Xe.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 ks(Ie.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new ks(Ie.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(Gt(as).subscribe(n=>{if(this.element?.paused){const o=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Oe(this.manifestUrlString,o+1e3,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...As.map(n=>M(this.element,n))).pipe(kr(as),A(n=>this.element?Ye(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async o=>{D(this.element);const c=this.element.playbackRate,d=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),h=tn*c,u=rn*c,l=sn*c;n=o>n?o:n;const p=d===0&&o<l,S=d!==0&&o<h+l&&o>=h,v=d!==0&&o<h;if(v||S){const b=n-(h+u),w=Math.trunc(d+b/c);let C;o?w>0?C=w:C=0:C=d,this.manifestUrlString=Oe(this.manifestUrlString,C,fe.DASH_CMAF_OFFSET_P)}(p||v||S)&&(await this.updateLive(),n=0)}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,Le({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:x.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.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(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Xe.REPRESENTATIOS_READY)}.bind(this));initBuffer(){D(this.element),this.state$.setState(Xe.RUNNING),this.subscription.add(O(...As.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:x.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Ie.VIDEO]:this.videoBufferManager,[Ie.AUDIO]:this.audioBufferManager,[Ie.TEXT]:null}[e]?.switchTo(t)}seek(e,t){D(this.element),D(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),si(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(Xe.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=Gt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:x.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 a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.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 ln{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class fn{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,a=t-this.camera.orientation.y,n=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:a,z:n},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 pn=`#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;}`,mn=`#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 rr{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 fn(this.params.fov,this.params.orientation),this.cameraRotationManager=new pn(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"),a=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(a,-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(mn,this.gl.VERTEX_SHADER),i=this.createShader(gn,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,a=e-i,n=t-s,o=e+i,c=t-s,d=e+i,h=t+s,u=e-i,l=t+s;return[a,n,o,c,d,h,u,l]}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 ar=class{scene3D;subscription=new se;videoState=new de(me.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new ot;droppedFramesManager=new Ai;videoTracks$=new g([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new qs;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ln({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=Tt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:L.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=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(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(_t(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Dt(this.video,t.playbackRate,i.playbackRateState$,s)),a(Ei(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===me.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Je.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();w(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,D)=>D.bitrate-b.bitrate),p=Array.from(u.video).sort((b,D)=>D.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const D=on(b);D&&this.audioTracks.push({track:D,representation:b})}for(const b of p){const D=nn(b);if(D){h.push({track:D,representation:b});const C=!this.params.tuning.isAudioDisabled&&dn(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const D=cn(b);D&&this.textTracks.push({track:D,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 v=this.selectVideoRepresentation();w(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Je.REPRESENTATIOS_READY&&(this.videoState.setState(me.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Je.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Re.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Re.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),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 o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(c.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:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=He(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=qt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===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===j.Requested&&i?.to!==f.PAUSED&&e!==me.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==me.STOPPED&&(this.videoState.startTransitionTo(me.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(me.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case me.STOPPED:this.videoState.startTransitionTo(me.READY),this.prepare();return;case me.READY:t===f.PAUSED?(this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case me.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case me.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(me.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===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new rr(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(){Pt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.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),yt(this.video)}},Sn=class extends ar{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 Ie;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Ie||(Ie={}));var lt;(function(r){r[r.ActiveLowLatency=0]="ActiveLowLatency",r[r.LiveWithTargetOffset=1]="LiveWithTargetOffset",r[r.LiveForwardBuffering=2]="LiveForwardBuffering",r[r.None=3]="None"})(lt||(lt={}));var Hi;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Hi||(Hi={}));var Ze;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Ze||(Ze={}));var Q;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(Q||(Q={}));var ai;(function(r){r.MP4="mp4",r.WEBM="webm"})(ai||(ai={}));var Yi;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Yi||(Yi={}));var ge;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ge||(ge={}));let nr=!1;try{nr=Wi().browser===us.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class bn{bufferFull$=new I;error$=new I;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 a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;nr&&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:L.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:L.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:N(t)}}}class tt{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 or extends tt{}class yn extends tt{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 Tn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class vn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class En extends tt{data;constructor(e){super(e),this.data=this.content}}class xt extends tt{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class kn extends xt{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,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class $n extends tt{parseChildrenBoxes(){return Bt(this.content)}}class An extends tt{parseChildrenBoxes(){return Bt(this.content)}}var Ht;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ht||(Ht={}));class wn extends xt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ht.MONOSCOPIC;break;case 1:this.stereoMode=Ht.TOP_BOTTOM;break;case 2:this.stereoMode=Ht.LEFT_RIGHT;break;case 3:this.stereoMode=Ht.STEREO_CUSTOM;break;case 4:this.stereoMode=Ht.RIGHT_LEFT;break}this.cursor+=1}}class Dn extends xt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Pn extends xt{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 xn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class Ln extends xt{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 Rn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class In extends tt{parseChildrenBoxes(){return Bt(this.content)}}class Cn extends xt{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class _n extends tt{parseChildrenBoxes(){return Bt(this.content)}}class Bn extends xt{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 Mn extends xt{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 On extends xt{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 Nn={ftyp:yn,moov:Tn,moof:vn,mdat:En,sidx:kn,trak:$n,mdia:xn,mfhd:Cn,tkhd:Ln,traf:_n,tfhd:Bn,tfdt:Mn,trun:On,minf:Rn,sv3d:An,st3d:wn,prhd:Dn,proj:In,equi:Pn,unknown:or};class Fn{createBox(e,t){const i=Nn[e];return i?new i(t):new or(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ki.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Ki=new Fn;function Si(r,e){const t=new Uint8Array(r.buffer),i=e.split("").map(n=>n.charCodeAt(0));let s=r.byteOffset,a=[];for(;s<t.byteLength;){if(t[s]===i[a.length]?a.push(t[s]):a=[],a.length===4){const o=new DataView(r.buffer,s-7,4).getUint32(0);return s-7+o>r.buffer.byteLength?null:Ki.createBox(e,new DataView(r.buffer,s-7))}s++}return null}function ns(r,e){const t=[];let i=r.byteOffset;for(;i<r.buffer.byteLength;){const s=Si(new DataView(r.buffer,i,r.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function Bt(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Ki.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Vn=new TextDecoder("ascii"),Un=r=>Vn.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Hn=r=>{const e=Ki.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Q.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Yn=r=>{const e=ns(r,"mdat"),t=ns(r,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],a=i.source.byteOffset,o=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(r.buffer,a,o)},Gn=(r,e)=>{const t=ns(r,"traf"),i=t[t.length-1].children.find(c=>c.type==="tfhd"),s=t[t.length-1].children.find(c=>c.type==="tfdt"),a=t[t.length-1].children.find(c=>c.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((c,d)=>c+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(s.baseMediaDecodeTime)+n)/e*1e3},zn=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Yi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Si(r,"sv3d")){e.is3dVideo=!0;const i=Si(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=Si(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=Si(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},qn={validateData:Un,parseInit:zn,getIndexRange:()=>{},parseSegments:Hn,parseFeedableSegmentChunk:Yn,getSegmentEndTime:Gn};var k;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(k||(k={}));var B;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(B||(B={}));const ws={[k.EBML]:{type:B.Master},[k.EBMLVersion]:{type:B.UnsignedInteger},[k.EBMLReadVersion]:{type:B.UnsignedInteger},[k.EBMLMaxIDLength]:{type:B.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:B.UnsignedInteger},[k.DocType]:{type:B.String},[k.DocTypeVersion]:{type:B.UnsignedInteger},[k.DocTypeReadVersion]:{type:B.UnsignedInteger},[k.Void]:{type:B.Binary},[k.Segment]:{type:B.Master},[k.SeekHead]:{type:B.Master},[k.Seek]:{type:B.Master},[k.SeekID]:{type:B.Binary},[k.SeekPosition]:{type:B.UnsignedInteger},[k.Info]:{type:B.Master},[k.TimestampScale]:{type:B.UnsignedInteger},[k.Duration]:{type:B.Float},[k.Tracks]:{type:B.Master},[k.TrackEntry]:{type:B.Master},[k.Video]:{type:B.Master},[k.Projection]:{type:B.Master},[k.ProjectionType]:{type:B.UnsignedInteger},[k.ProjectionPrivate]:{type:B.Master},[k.Chapters]:{type:B.Master},[k.Cluster]:{type:B.Master},[k.Timestamp]:{type:B.UnsignedInteger},[k.SilentTracks]:{type:B.Master},[k.SilentTrackNumber]:{type:B.UnsignedInteger},[k.Position]:{type:B.UnsignedInteger},[k.PrevSize]:{type:B.UnsignedInteger},[k.SimpleBlock]:{type:B.Binary},[k.BlockGroup]:{type:B.Master},[k.EncryptedBlock]:{type:B.Binary},[k.Attachments]:{type:B.Master},[k.Tags]:{type:B.Master},[k.Cues]:{type:B.Master},[k.CuePoint]:{type:B.Master},[k.CueTime]:{type:B.UnsignedInteger},[k.CueTrackPositions]:{type:B.Master},[k.CueTrack]:{type:B.UnsignedInteger},[k.CueClusterPosition]:{type:B.UnsignedInteger},[k.CueRelativePosition]:{type:B.UnsignedInteger},[k.CueDuration]:{type:B.UnsignedInteger},[k.CueBlockNumber]:{type:B.UnsignedInteger},[k.CueCodecState]:{type:B.UnsignedInteger},[k.CueReference]:{type:B.Master},[k.CueRefTime]:{type:B.UnsignedInteger}},dr=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Gi(r,t),s=i in ws,a=s?ws[i].type:B.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Gi(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Gi=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},mt=(r,e)=>{switch(e){case B.SignedInteger:return r.getInt8(0);case B.UnsignedInteger:return Gi(r);case B.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case B.String:return new TextDecoder("ascii").decode(r);case B.UTF8:return new TextDecoder("utf-8").decode(r);case B.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case B.Master:return r;case B.Binary:return r;default:N(e)}},ni=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=dr(i);if(!e(s))return;s.type===B.Master&&ni(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},Wn=r=>{if(r.getUint32(0)!==k.EBML)return!1;let e,t,i;const s=dr(r);return ni(s.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=mt(o,n):a===k.DocType?t=mt(o,n):a===k.DocTypeReadVersion&&(i=mt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},cr=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],Qn=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],jn=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ni(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===k.SeekID){const b=mt(S,p);d=Gi(b)}else l!==k.SeekPosition&&(d=void 0);return l===k.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===k.Info?a=!0:l===k.SeekHead?n=!0:l===k.TimestampScale?i=mt(S,p):l===k.Duration?s=mt(S,p):l===k.SeekPosition&&d===k.Cues?c=mt(S,p):l===k.Tracks?ni(S,({tag:b,type:D,value:C})=>b===k.ProjectionType?(h=mt(C,D)===1,!1):!0):a&&n&&cr.includes(l)&&(o=!0),!o}),w(e,"Failed to parse webm Segment start"),w(t,"Failed to parse webm Segment end"),w(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:c,is3dVideo:h,stereoMode:u,projectionType:Yi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Jn=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Xn=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ni(r,({tag:o,type:c,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&s(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=mt(d,c));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=mt(d,c));break;default:t&&cr.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:Q.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Kn=r=>{let e=0,t=!1;try{ni(r,i=>i.tag===k.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Qn.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Zn={validateData:Wn,parseInit:jn,getIndexRange:Jn,parseSegments:Xn,parseFeedableSegmentChunk:Kn},Ds=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Xt=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},eo=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=Ds(l);else if(p){const m=Ds(p);P(m)&&(u=m)}else v&&(u=parseInt(v,10));let b=0;const D=a.getAttribute("profiles")?.split(",")??[],C=D.includes(Hi.WEBM_AS_IN_FFMPEG)||D.includes(Hi.WEBM_AS_IN_SPEC)?ai.WEBM:ai.MP4;for(const m of o){const $=m.getAttribute("mimeType"),x=m.getAttribute("codecs"),H=m.getAttribute("contentType")??$?.split("/")[0],q=m.getAttribute("profiles")?.split(",")??[],F=m.querySelectorAll("Representation"),G=m.querySelector("SegmentTemplate");if(H===Ie.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=m.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Ie.TEXT].push({id:V,lang:z,isAuto:ke,kind:Ie.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??$,z=T.getAttribute("codecs")??x??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=m.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,Ce=pe?ji(pe):void 0,dt=T.getAttribute("id")??(b++).toString(10),ci=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,Wt=`${dt}@${ci}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Fe=[...D,...q,...ye];let De;const Et=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(Et){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,ct]=Ae.split("-").map(Ge=>parseInt(Ge,10)),Ve={from:Pe,to:ct},it=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[Mt,kt]=it?it.split("-").map(Ge=>parseInt(Ge,10)):[],st=it?{from:Mt,to:kt}:void 0;De={type:Ze.BYTE_RANGE,url:we,initRange:Ve,indexRange:st}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),ct=Te.getAttribute("initialization")??"",Ve=Te.getAttribute("media"),it=parseInt(Te.getAttribute("startNumber")??"",10)??1,Mt=Xt(ct,Ae);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");const kt=Te.querySelectorAll("SegmentTimeline S")??[],st=[];let Ge=0,Ot="",ze=0;if(kt.length){let qe=it,ve=0;for(const rt of kt){const Ue=parseInt(rt.getAttribute("d")??"",10),ut=parseInt(rt.getAttribute("r")??"",10)||0,$t=parseInt(rt.getAttribute("t")??"",10);ve=Number.isFinite($t)?$t:ve;const ui=Ue/Pe*1e3,Di=ve/Pe*1e3;for(let Qt=0;Qt<ut+1;Qt++){const gr=Xt(Ve,{...Ae,segmentNumber:qe.toString(10),segmentTime:(ve+Qt*Ue).toString(10)}),ms=(Di??0)+Qt*ui,Sr=ms+ui;qe++,st.push({time:{from:ms,to:Sr},url:gr})}ve+=(ut+1)*Ue,Ge+=(ut+1)*ui}ze=ve/Pe*1e3,Ot=Xt(Ve,{...Ae,segmentNumber:qe.toString(10),segmentTime:ve.toString(10)})}else if(P(u)){const ve=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,rt=Math.ceil(u/ve);let Ue=0;for(let ut=1;ut<rt;ut++){const $t=Xt(Ve,{...Ae,segmentNumber:ut.toString(10),segmentTime:Ue.toString(10)});st.push({time:{from:Ue,to:Ue+ve},url:$t}),Ue+=ve}ze=Ue,Ot=Xt(Ve,{...Ae,segmentNumber:rt.toString(10),segmentTime:Ue.toString(10)})}const Nt={time:{from:ze,to:1/0},url:Ot};De={type:Ze.TEMPLATE,baseUrl:we,segmentTemplateUrl:Ve,initUrl:Mt,totalSegmentsDurationMs:Ge,segments:st,nextSegmentBeyondManifest:Nt,timescale:Pe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ye={video:Ie.VIDEO,audio:Ie.AUDIO,text:Ie.TEXT}[te];Ye&&s[Ye].push({id:Wt,kind:Ye,segmentReference:De,profiles:Fe,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:Ce,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},to=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?oi(a):void 0)??Ct({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},io=({id:r,bitrate:e})=>({id:r,bitrate:e}),so=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},ro=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),Ps=r=>"size"in r,jt=r=>r.type===Ze.TEMPLATE,os=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);class xs{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);playingRepresentationInit$=new g(void 0);error$=new I;gaps=[];subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new et;destroyAbortController=new et;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:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:c,compatibilityMode:d=!1,manifest:h}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=c,this.isLive=!!h?.dynamic,this.container=i,i){case ai.MP4:this.containerParser=qn;break;case ai.WEBM:this.containerParser=Zn;break;default:N(i)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);w(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new bn(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Vi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);w(i,"No init buffer for starting representation"),w(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(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);w(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),w(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 a=this.getCurrentPosition();P(a)&&(this.isLive||(i.forEach(n=>n.status=Q.NONE),this.pruneBuffer(a,1/0,!0)),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(w(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=He(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Vi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=He(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===Q.FED&&!o.length&&He(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=i.at(-1);c&&c.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+s}),i=a.time.to;P(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 a=0,n=t.length-1;do s.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-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=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d||!jt(d.segmentReference))return;const h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);w(i);const s=this.segments.get(t);w(s,"No segments for starting representation");const a=this.initData.get(t);if(w(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!jt(t.segmentReference))return;const i=t.segmentReference.segments.map(o=>({...o,status:Q.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.floor(a)>=Math.floor(o.time.from)&&Math.floor(a)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!jt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),a=Xt(i.segmentTemplateUrl,{segmentTime:s}),n=this.segments.get(t.id)??[],o=n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||n.push({status:Q.NONE,time:{from:e.segment.time.to,to:1/0},url:a})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,D=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+D||p<=i+D;return(u===Q.NONE||u===Q.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!si(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==Ze.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===Q.NONE||l.status===Q.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){t.segmentReference.type===Ze.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Q.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:a,url:n,signal:o,onProgress:c,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await oe(o,async function*(){const h=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,h))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:c,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const u=new DataView(h);if(this.isActiveLowLatency()){const l=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(u,l)}c&&s.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(u,o),s.segment.status=Q.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!os(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const c of e)c.status=Q.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await oe(n,async function*(){const c=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:s,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(c){if(!os(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}}prepareByteRangeFetchSegmentParams(e,t){if(jt(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:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:s,signal:a,onProgress:(c,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!jt(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:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,u)=>{if(!a.aborted)try{const l=this.onSomeTemplateDataLoaded({dataView:h,loaded:u,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:s,signal:a,onProgress:d,onProgressTasks:o}}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&&P(i)&&(t=He(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:c}=o;if(o.representationId===t){if(a.aborted){s();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(d);h?.byteLength&&(c.status=Q.PARTIALLY_FED,o.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),o.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const c=o.segmentReference.type,d=e.byteLength;for(const h of this.activeSegments){const{segment:u}=h,l=c===Ze.BYTE_RANGE,p=l?u.byte.to-u.byte.from+1:d;if(h.representationId!==t||!(!l||u.byte.from>=i&&u.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const v=l?u.byte.from-i:0,b=l?u.byte.to-i:e.byteLength,D=v<s,C=b<=s;if(u.status===Q.DOWNLOADING&&D&&C){u.status=Q.DOWNLOADED;const m=new DataView(e.buffer,e.byteOffset+v,p);this.sourceBufferTaskQueue.append(m,a).then($=>$&&!a.aborted?this.onSegmentFullyAppended(h,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&D&&(h.loadedBytes=Math.min(p,s-v),h.loadedBytes>h.feedingBytes)){const m=new DataView(e.buffer,e.byteOffset+v+h.feedingBytes,h.loadedBytes-h.feedingBytes),$=h.loadedBytes===p?m:this.containerParser.parseFeedableSegmentChunk(m);$?.byteLength&&(u.status=Q.PARTIALLY_FED,h.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(x=>{if(a.aborted)n();else if(x)h.fedBytes+=$.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Q.FED,Ps(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===Q.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=Q.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.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,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Fi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:c,dataView:d,segments:h}=o,u=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,u);let l=h;this.isLive&&jt(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h=Ps(d)?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===Q.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===Q.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===Q.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===Q.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!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 a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(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),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==Q.FED&&a!==Q.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=Q.PARTIALLY_EJECTED:s.status=Q.NONE)}}}var Zt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Zt||(Zt={}));class ao{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new et;subscription=new se;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}=fs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=It(t));const i=yield zt(t,{signal:this.abortAllController.signal}).catch(fi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Zt.HEADER:Zt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let d=e;const h=new Headers;if(i)switch(t){case Zt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Zt.PARAM:{const F=new URL(d,location.href);F.searchParams.append("bytes",`${i.from}-${i.to}`),d=F.toString();break}default:N(t)}this.requestQuic&&(d=It(d));let u=this.abortAllController.signal,l;if(n){const F=new et;if(l=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{F.abort()}catch(G){fi(G)}}),this.abortAllController.signal.aborted||n.aborted)try{F.abort()}catch(G){fi(G)}u=F.signal}const p=ne(),S=yield zt(d,{priority:a,headers:h,signal:u}).catch(fi),v=ne();if(!S)return l?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-p),!S.ok||!S.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));if(this.onHeadersReceived(S.headers),!s&&!o)return l?.unsubscribe(),S.arrayBuffer();const[b,D]=S.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(D,c);let m=0,$=new Uint8Array(0),x=!1;const H=F=>{l?.unsubscribe(),x=!0,fi(F)},q=oe(u,async function*({done:F,value:G}){if(m===0&&this.lastRequestFirstBytes$.next(ne()-p),u.aborted){l?.unsubscribe();return}if(!F&&G){const T=new Uint8Array($.length+G.length);T.set($),T.set(G,$.length),$=T,m+=G.byteLength,s?.(new DataView($.buffer),m),yield C?.read().then(q,H)}}.bind(this));return yield C?.read().then(q,H),l?.unsubscribe(),x?null:$.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ze.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ze.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ze.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const D=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!D)return null;v=new DataView(D)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==Ze.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(n=>({...n,status:Q.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const fi=r=>{if(!os(r))throw r},ds=1e3,zi=(r,e,t)=>t*e+(1-t)*r,ur=(r,e)=>r.reduce((t,i)=>t+i,0)/e,no=(r,e,t,i)=>{let s=0,a=t;const n=ur(r,e),o=e<i?e:i;for(let c=0;c<o;c++)r[a]>n?s++:s--,a=(r.length+a-1)%r.length;return Math.abs(s)===o};class ps{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 g(e.initial),this.debounced$=new g(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ft(`raw_${t}`),this.smoothedSeries$=new ft(`smoothed_${t}`),this.reportedSeries$=new ft(`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 o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*s,n=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>a||this.smoothed<n)&&(Y(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 oo extends ps{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=zi(this.slow,e,this.params.emaAlphaSlow),this.fast=zi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class co extends ps{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ur(this.pastMeasures,this.takenMeasures);this.emaSmoothed=zi(this.emaSmoothed,e,this.params.emaAlpha);const i=no(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class uo extends ps{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?zi(this.smoothed,e,this.params.emaAlpha):e}}class cs{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new oo({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new co({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 uo({initial:e,label:"liveEdgeDelay",...t})}}const ho=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)},Ls=["timeupdate","progress","play","seeked","stalled","waiting"];var Xe;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Xe||(Xe={}));let lo=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Xe.NONE);currentVideoRepresentation$=new g(void 0);currentVideoRepresentationInit$=new g(void 0);error$=new I;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);isLive$=new g(!1);liveDuration$=new g(0);liveAvailabilityStartTime$=new g(void 0);bufferLength$=new g(0);liveLoadBufferLength$=new g(0);livePositionFromPlayer$=new g(0);liveEstimatedDelay;liveWaitingEventCallback;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new et;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ao({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=cs.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.liveWaitingEventCallback=Pr(this._liveWaitingEventCallback,this.tuning.dashCmafLive.maxWaitingDuration)}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Me(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Xe.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Xe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(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:L.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=eo(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Ie.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,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){w(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.liveLastSeekOffset=e,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Me(this.manifestUrlString,e,fe.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=oe(this.destroyController.signal,async function*(e,t){w(this.manifest),w(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Xe.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 xs(Ie.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new xs(Ie.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(Gt(ds).subscribe(n=>{if(this.element?.paused){const o=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Me(this.manifestUrlString,o+ds,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...Ls.map(n=>M(this.element,n))).pipe(A(n=>this.element?He(this.element.buffered,this.element.currentTime*1e3):0),le(),K(n=>!!n)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(K(o=>this.isActiveLowLatency&&!!o)).subscribe(o=>this.liveEstimatedDelay.next(o))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(o=>{if(!this.isActiveLowLatency)return;const c=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,d=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=o-c;let l=1+Math.sign(u)*h;Math.abs(u)<d?l=1:Math.abs(u)>d*2&&(l=1+Math.sign(u)*h*2),ho(this.element,l)})),this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(xe({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:o,bufferLength:c})=>{if(w(this.element),this.liveWaitingEventCallback.cancel(),this.isUpdatingLive)return;const d=this.element.playbackRate,h=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,l=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*d),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*d,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*d,v=this.isActiveLowLatency?c:o;let b=lt.None;if(this.isActiveLowLatency?b=lt.ActiveLowLatency:v<l+S&&v>=l?b=lt.LiveWithTargetOffset:h!==0&&v<l&&(b=lt.LiveForwardBuffering),isFinite(o)&&(n=o>n?o:n),b===lt.LiveForwardBuffering||b===lt.LiveWithTargetOffset){const D=n-(l+p),C=Math.trunc(h+D/d);let m;o?C>0?m=C:m=0:m=h,this.manifestUrlString=Me(this.manifestUrlString,m,fe.DASH_CMAF_OFFSET_P)}b!==lt.None&&b!==lt.ActiveLowLatency&&(n=0,this.updateLive())}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,xe({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.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(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Xe.REPRESENTATIOS_READY)}.bind(this));initBuffer(){w(this.element),this.state$.setState(Xe.RUNNING),this.subscription.add(O(...Ls.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&si(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{[Ie.VIDEO]:this.videoBufferManager,[Ie.AUDIO]:this.audioBufferManager,[Ie.TEXT]:null}[e]?.switchTo(t)}seek(e,t){w(this.element),w(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),si(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(Xe.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:L.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=Gt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:L.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 a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.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 hr{scene3D;subscription=new se;videoState=new de(ge.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new ot;droppedFramesManager=new Ai;videoTracks$=new g([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new qs;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new lo({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=Tt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:L.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=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(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(_t(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Dt(this.video,t.playbackRate,i.playbackRateState$,s)),a(Ei(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Xe.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();w(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,D)=>D.bitrate-b.bitrate),p=Array.from(u.video).sort((b,D)=>D.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const D=io(b);D&&this.audioTracks.push({track:D,representation:b})}for(const b of p){const D=to(b);if(D){h.push({track:D,representation:b});const C=!this.params.tuning.isAudioDisabled&&so(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const D=ro(b);D&&this.textTracks.push({track:D,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 v=this.selectVideoRepresentation();w(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Xe.REPRESENTATIOS_READY&&(this.videoState.setState(ge.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Xe.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Ie.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Ie.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),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 o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(c.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:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=He(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=qt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===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===j.Requested&&i?.to!==f.PAUSED&&e!==ge.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.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(ge.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case ge.STOPPED:this.videoState.startTransitionTo(ge.READY),this.prepare();return;case ge.READY:t===f.PAUSED?(this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case ge.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ge.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ge.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===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new rr(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(){Pt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.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),yt(this.video)}}class fo extends hr{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 po=class extends ar{constructor(e){super(e),this.liveOffset=new $i}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(xe({interval:Gt(as),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===me.PLAYING){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(xe({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a: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===f.PAUSED&&i===me.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}};class mo extends hr{constructor(e){super(e),this.liveOffset=new $i}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(xe({interval:Gt(ds),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ge.PLAYING&&!this.player.isActiveLowLatency){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(xe({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a: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===f.PAUSED&&i===ge.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const ht={};var ie;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ie||(ie={}));const pi=(r,e)=>new Qi(t=>{const i=(s,a)=>t.next(a);return r.on(e,i),()=>r.off(e,i)});class go{subscription=new se;videoState=new de(ie.INITIALIZING);video;params;hls;textTracksManager=new ot;trackLevels=new Map;constructor(e){this.video=bt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),yt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:L.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||(ht.Hls=s.default,ht.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){w(ht.Hls,"hls.js not loaded"),this.hls=new ht.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ie.STOPPED)}subscribe(){w(ht.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:L.WTF,message:"HlsJsProvider internal logic error",thrown:d})},s=Tt(this.video),a=(d,h)=>this.subscription.add(d.subscribe(h,i));a(s.timeUpdate$,t.position$),a(s.durationChange$,t.duration$),a(s.ended$,t.endedEvent$),a(s.looped$,t.loopedEvent$),a(s.error$,t.error$),a(s.isBuffering$,t.isBuffering$),a(s.currentBuffer$,t.currentBuffer$),a(s.loadStart$,t.firstBytesEvent$),a(s.playing$,t.firstFrameEvent$),a(s.canplay$,t.canplay$),a(s.seeked$,t.seekedEvent$),a(s.inPiP$,t.inPiP$),a(s.inFullscreen$,t.inFullscreen$),this.subscription.add(_t(this.video,e.isLooped,i)),this.subscription.add(St(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(pi(this.hls,ht.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:L.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),R(e.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),R(e.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),a(pi(this.hls,ht.Events.MANIFEST_PARSED).pipe(A(({levels:d})=>d.reduce((h,u)=>{const l=u.name||u.height.toString(10),{width:p,height:S}=u,v=oi(u.attrs.QUALITY??"")??Ct({width:p,height:S});if(!v)return h;const b=u.attrs["FRAME-RATE"]?parseFloat(u.attrs["FRAME-RATE"]):void 0,D={id:l.toString(),quality:v,bitrate:u.bitrate/1e3,size:{width:p,height:S},fps:b};return this.trackLevels.set(l,{track:D,level:u}),h.push(D),h},[]))),t.availableVideoTracks$),a(pi(this.hls,ht.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const h=[];for(const u of d.subtitleTracks){const l=u.name,p=u.attrs.URI||"",S=u.lang,v="internal";h.push({id:l,url:p,language:S,type:v})}e.internalTextTracks.startTransitionTo(h)}}),a(pi(this.hls,ht.Events.LEVEL_LOADING).pipe(A(({url:d})=>Ne(d))),t.hostname$),this.subscription.add(nt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>Array.from(this.trackLevels.values()).find(({level:h})=>h===d)?.track,o=pi(this.hls,ht.Events.LEVEL_SWITCHED).pipe(A(({level:d})=>n(this.hls.levels[d])));o.pipe(K(P)).subscribe(t.currentVideoTrack$,i),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{if(Y(d))return;const h=this.trackLevels.get(d.id)?.level;if(!h)return;const u=this.hls.levels.indexOf(h),l=this.hls.currentLevel,p=this.hls.levels[l];!p||h.bitrate>p.bitrate?this.hls.nextLevel=u:(this.hls.loadLevel=u,this.hls.loadLevel=u)},{changed$:o,onError:i})),a(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(c.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!==ie.INITIALIZING)switch(i?.to!==f.PAUSED&&s.state===j.Requested&&this.seek(s.position),t){case f.STOPPED:switch(e){case ie.STOPPED:break;case ie.READY:case ie.PLAYING:case ie.PAUSED:this.stop();break;default:N(e)}break;case f.READY:switch(e){case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PLAYING:case ie.PAUSED:break;default:N(e)}break;case f.PLAYING:switch(e){case ie.PLAYING:break;case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PAUSED:this.playIfAllowed();break;default:N(e)}break;case f.PAUSED:switch(e){case ie.PAUSED:break;case ie.STOPPED:this.prepare();break;case ie.READY:this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case ie.PLAYING:this.pause();break;default:N(e)}break;default:N(t)}};prepare(){this.videoState.startTransitionTo(ie.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ie.PLAYING),await Pt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:t}))||(this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ie.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(ie.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}}const Rs="X-Playback-Duration";var Is=async r=>{const e=await zt(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Rs)?parseInt(e.headers.get(Rs),10):void 0};const So=r=>{let e=null;if(r.QUALITY&&(e=oi(r.QUALITY)),!e&&r.RESOLUTION){const[t,i]=r.RESOLUTION.split("x").map(s=>parseInt(s,10));e=Ct({width:t,height:i})}return e??null},lr=async(r,e=r)=>{const s=(await(await zt(r)).text()).split(`
46
- `),a=[],n=[];for(let o=0;o<s.length;o++){const c=s[o],d=c.match(/^#EXT-X-STREAM-INF:(.+)/),h=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!h)){if(d){const u=Object.fromEntries(d[1].split(",").map(C=>C.split("="))),l=u.QUALITY??`stream-${u.BANDWIDTH}`,p=So(u);let S;u.BANDWIDTH&&(S=parseInt(u.BANDWIDTH,10)/1e3||void 0),!S&&u["AVERAGE-BANDWIDTH"]&&(S=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let b;if(u.RESOLUTION){const[C,m]=u.RESOLUTION.split("x").map($=>parseInt($,10));C&&m&&(b={width:C,height:m})}const D=new URL(s[++o],e).toString();p&&a.push({id:l,quality:p,url:D,bandwidth:S,size:b,fps:v})}if(h){const u=Object.fromEntries(h[1].split(",").map(v=>v.split("=")).map(([v,b])=>[v,b.replace(/^"|"$/g,"")])),l=u.URI?.replace(/playlist$/,"subtitles.vtt"),p=u.LANGUAGE,S=u.NAME;l&&p&&n.push({type:"internal",id:p,label:S,language:p,url:l,isAuto:!1})}}}return{qualityManifests:a,textTracks:n}};var ce;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(ce||(ce={}));class bo{subscription=new se;videoState=new de(ce.STOPPED);video;params;textTracksManager=new ot;masterManifest;manifests$=new g([]);maxSeekBackTime$;liveOffset=new $i;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:je.INVARIANT,url:this.params.source.url},lr(Me(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:L.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(Ne(this.params.source.url)),this.maxSeekBackTime$=new g(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:L.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=Tt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.ended$,e.endedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(St(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(le(),A(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Ne(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===ce.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===j.Requested&&this.seek(o.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(xe({startTime:this.manifestStartTime$.pipe(K(P)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),i)),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Oe(["init"])).pipe(Qe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),yt(this.video)}prepare(){const e=this.selectManifest();if(Y(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:o,min:c}=t?.to??i??{};for(const[d,h]of[[o,"mq"],[c,"lq"]]){const u=String(parseFloat(d||""));h&&u&&s.set(h,u)}}const a=this.params.format===y.HLS_LIVE_CMAF?fe.DASH_CMAF_OFFSET_P:fe.OFFSET_P,n=Me(s.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",n),this.video.load(),Is(n).then(o=>{if(!Y(o))this.maxSeekBackTime$.next(o);else{const c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Y(c)||!isFinite(c))try{zt(n).then(d=>d.text()).then(d=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(h){const u=new URL(h,n).toString();Is(u).then(l=>{Y(l)||this.maxSeekBackTime$.next(l)})}})}catch{}}})}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.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(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.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(ce.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(ce.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==f.PAUSED&&d.state===j.Requested){this.videoState.startTransitionTo(ce.READY),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case ce.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ce.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(ce.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===f.PAUSED&&(R(this.params.desiredState.playbackState,f.PAUSED),this.liveOffset.pause());return;case ce.CHANGING_MANIFEST:break;default:return N(t)}}}var he;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(he||(he={}));class yo{subscription=new se;videoState=new de(he.STOPPED);video;params;textTracksManager=new ot;masterManifest;manifests$=new g([]);constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:je.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),lr(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:L.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(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:L.WTF,message:"HlsProvider internal logic error",thrown:o})},s=Tt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c));if(a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(St(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===he.READY&&this.videoState.setState(he.READY),this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Ne(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===he.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===j.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i)),!kr()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(O(M(o,"addtrack"),M(o,"removetrack"),M(o,"change"),Oe(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},i))}const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Oe(["init"])).pipe(Qe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),yt(this.video)}prepare(){const e=this.selectManifest();if(Y(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:a,min:n}=t?.to??i??{};for(const[o,c]of[[a,"mq"],[n,"lq"]]){const d=String(parseFloat(o||""));c&&d&&s.set(c,d)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.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(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.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(he.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===he.STOPPED){this.videoState.startTransitionTo(he.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(he.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:u}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:u*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&d.state===j.Requested&&this.seek(d.position),t){case he.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed());return;case he.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case he.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;case he.CHANGING_MANIFEST:break;default:return N(t)}}}var Se;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Se||(Se={}));class To{subscription=new se;videoState=new de(Se.STOPPED);video;trackUrls={};params;textTracksManager=new ot;constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const a=s.toString(10);this.trackUrls[a]={track:{quality:t,id:a},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=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},s=Tt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(St(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Se.READY&&this.videoState.setState(Se.READY);const o=this.params.desiredState.videoTrack.getTransition();o&&P(o.to)&&(this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track)),this.videoState.getState()===Se.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),yt(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;w(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];w(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=It(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ne(t))}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.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===f.STOPPED){e!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.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(Se.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!==Se.READY&&!n){this.handleQualityLimitTransition(a.to.max);return}if(e===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){const{currentTime:c}=this.video;this.prepare(),o.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==f.PAUSED&&o.state===j.Requested&&this.seek(o.position),e){case Se.READY:t===f.READY?R(this.params.desiredState.playbackState,f.READY):t===f.PAUSED?(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Se.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(o=>!Yt(o.track.quality)&&Ys(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[a??"0"]?.track;if(s&&n&&is(n.quality,s.quality)&&(t=s),!t){const o=Object.values(this.trackUrls).filter(d=>!Yt(d.track.quality)&&ei(d.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(a=>a.track);t=qt(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 Cs=["stun:videostun.mycdn.me:80"],vo=1e3,Eo=3,ts=()=>null;class ko{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=ts;externalStopCallback=ts;externalErrorCallback=ts;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:Cs}]};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:L.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),vo)}normalizeOptions(e={}){const t={stunServerList:Cs,maxRetryNumber:Eo,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ue;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ue||(ue={}));class $o{subscription;params;log;video;videoState=new de(ue.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=bt(e.container),this.liveStreamClient=new ko(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),yt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(this.videoState.stateChangeStarted$.pipe(A(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=Tt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(s.timeUpdate$,e.liveTime$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ue.READY&&this.videoState.setState(ue.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(St(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ue.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(f.STOPPED);break;case ue.READY:break;case ue.PAUSED:t.playbackState.setState(f.PAUSED);break;case ue.PLAYING:t.playbackState.setState(f.PLAYING);break;default:return N(n.to)}},i)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:je.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,f.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ue.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:L.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.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===f.STOPPED){e!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.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(ue.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===ue.STOPPED){this.videoState.startTransitionTo(ue.READY),this.prepare();return}if(a){this.prepare();return}switch(e){case ue.READY:t===f.PAUSED?(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed());return;case ue.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ue.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}class _s{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 fr=Wi().device===$r.Android,qi=document.createElement("video"),Ao='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wo='video/mp4; codecs="hev1.1.6.L93.B0"',pr='video/webm; codecs="vp09.00.10.08"',mr='video/webm; codecs="av01.0.00M.08"',Do='audio/mp4; codecs="mp4a.40.2"',Po='audio/webm; codecs="opus"',at={mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(qi.canPlayType?.("application/x-mpegurl")||qi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},We={mp4:!!qi.canPlayType?.("video/mp4"),webm:!!qi.canPlayType?.("video/webm"),cmaf:!0},gt={h264:!!window.MediaSource?.isTypeSupported?.(Ao),h265:!!window.MediaSource?.isTypeSupported?.(wo),vp9:!!window.MediaSource?.isTypeSupported?.(pr),av1:!!window.MediaSource?.isTypeSupported?.(mr),aac:!!window.MediaSource?.isTypeSupported?.(Do),opus:!!window.MediaSource?.isTypeSupported?.(Po)},Jt=(gt.h264||gt.h265)&&gt.aac;var Rt;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Rt||(Rt={}));var wt;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(wt||(wt={}));let Ft;const xo=async()=>{if(!window.navigator.mediaCapabilities)return;const r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:mr}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:pr}})]);Ft={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{xo()}catch(r){console.error(r)}const ki=at.hls&&We.mp4,Lo=()=>Object.keys(gt).filter(r=>gt[r]),Ro=(r,e=!1)=>r.filter(t=>{switch(t){case y.DASH:return at.mse&&We.mp4&&Jt;case y.DASH_SEP:return at.mse&&We.mp4&&Jt;case y.DASH_WEBM:return at.mse&&We.webm&&gt.vp9&&gt.opus;case y.DASH_WEBM_AV1:return at.mse&&We.webm&&gt.av1&&gt.opus;case y.DASH_LIVE:return at.mse&&We.mp4&&Jt;case y.DASH_LIVE_CMAF:return at.mse&&We.mp4&&Jt&&We.cmaf;case y.DASH_ONDEMAND:return at.mse&&We.mp4&&Jt;case y.HLS:case y.HLS_ONDEMAND:return ki||e&&at.mse&&We.mp4&&Jt;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return ki;case y.MPEG:return We.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return at.webrtc&&at.ws&&gt.h264&&(We.mp4||We.webm);default:return N(t)}}),mi=r=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(r){case Rt.VP9:return[e,t];case Rt.AV1:return[t,e];case Rt.NONE:return[];case Rt.SMOOTH:return Ft?Ft[t].smooth?[t,e]:Ft[e].smooth?[e,t]:[t,e]:[e,t];case Rt.POWER_EFFICIENT:return Ft?Ft[t].powerEfficient?[t,e]:Ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:N(r)}return[e,t]},Io=({webmCodec:r,androidPreferredFormat:e})=>{if(fr)switch(e){case wt.MPEG:return[y.MPEG,...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case wt.HLS:return[y.HLS,y.HLS_ONDEMAND,...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case wt.DASH:return[...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return ki?[...mi(r),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},Co=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],s=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...s],n=[...s,...i];let o;if(fr)switch(r){case wt.DASH:{o=a;break}case wt.HLS:case wt.MPEG:{o=n;break}}else ki?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Bs=r=>r?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var _o=r=>new Qi(e=>{const t=new se,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(A(({from:d,to:h})=>`${d}-${h}`)),s=r.desiredPlaybackState$.stateChangeEnded$,a=r.providerChanged$.pipe(A(({type:d})=>d!==void 0)),n=new I;let o=0,c="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),r.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(c),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Bo={cacheDuration:12e4},Mo={chunkDuration:5e3,maxParallelRequests:5};class Oo{current$=new g({type:void 0});providerError$=new I;noAvailableProvidersError$=new I;providerOutput={position$:new g(0),duration$:new g(1/0),volume$:new g({muted:!1,volume:1}),currentVideoTrack$:new g(void 0),availableVideoTracks$:new g([]),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),autoVideoTrackLimitingAvailable$:new g(!1),autoVideoTrackLimits$:new g(void 0),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new I,warning$:new I,willSeekEvent$:new I,seekedEvent$:new I,loopedEvent$:new I,endedEvent$:new I,firstBytesEvent$:new I,firstFrameEvent$:new I,canplay$:new I,isLive$:new g(void 0),isLowLatency$:new g(!1),canChangePlaybackSpeed$:new g(!0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),inPiP$:new g(!1),inFullscreen$:new g(!1),element$:new g(void 0),availableSources$:new g(void 0),is3DVideo$:new g(!1)};subscription=new se;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Ro([...Co(this.params.tuning),...Io(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>P(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let a=[];i?a=[i]:s.length?a=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new _s(a);const n=[...Bs(!0),...Bs(!1)];this.chromecastFormatsIterator=new _s(n.filter(o=>P(e.sources[o]))),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(Y(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:L.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!==j.None;if(this.params.desiredState.seekState.setState({state:j.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return N(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return w(o),new va({...n,source:o,config:Bo})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return w(o),this.params.tuning.useDashJs?new bs({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new fo({...n,source:o}):new Sn({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return w(o),this.params.tuning.useDashJsCMAF?new bs({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new mo({...n,source:o}):new po({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return w(o),ki||!this.params.tuning.useHlsJs?new yo({...n,source:o}):new go({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return w(o),new bo({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return w(o),new To({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return w(o),new ga({...n,source:o,config:{...Mo,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return w(o),new $o({container:i,source:o,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return w(o),new Or({connection:o,meta:a,container:i,source:t,format:e,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return N(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return N(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return N(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 a=new URL(s);return a.host=t,a.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,a])=>[s,i(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,i=0;return e.add(O(this.providerOutput.error$,_o({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(A(s=>({id:`ProviderHangup:${s}`,category:L.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(K(({to:a})=>a===f.PLAYING),be()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const a=this.current$.getValue().destination;if(a===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(_e.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===L.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(a??_e.SCREEN)}})),e}}const No=5e3,Ms="one_video_throughput",Os="one_video_rtt",yi=window.navigator.connection,Ns=()=>{const r=yi?.downlink;if(P(r)&&r!==10)return r*1e3},Fs=()=>{const r=yi?.rtt;if(P(r)&&r!==3e3)return r},Vs=(r,e,t)=>{const i=t*8,s=i/r;return i/(s+e)};class Ti{throughput;rtt;subscription=new se;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Ti.load(Ms)||(e.useBrowserEstimation?Ns():void 0)||No,i=Ti.load(Os)??(e.useBrowserEstimation?Fs():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(i),this.rttAdjustedThroughput$=new g(Vs(t,i,e.rttPenaltyRequestSize)),this.throughput=cs.getSmoothedValue(t,-1,e),this.rtt=cs.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=Ns();n&&this.throughput.next(n);const o=Fs();P(o)&&this.rtt.next(o)};yi&&"onchange"in yi&&this.subscription.add(M(yi,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{Zi.set(Ms,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{Zi.set(Os,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(xe({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(A(({throughput:s,rtt:a})=>Vs(s,a,e.rttPenaltyRequestSize)),K(s=>{const a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ne();const s=new se;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(M(e,"progress").pipe(be()).subscribe(a=>{t=a.loaded,i=ne()}));break;case 1:case 0:s.add(M(e,"loadstart").subscribe(()=>{t=0,i=ne()}));break}s.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),c=n-t,d=o-i;this.addRawSpeed(c,d,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,a=ne(),n=0,o=ne();const c=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},d=async({done:h,value:u})=>{if(h)!t&&this.addRawSpeed(s,ne()-a,1),this.concurrentDownloads.delete(e);else if(u){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=u.byteLength;else{const p=o-a;p&&this.addRawSpeed(n,p,1,t),n=u.byteLength,a=ne()}o=ne()}else s+=u.byteLength,n+=u.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await i?.read().then(d,c)}};this.concurrentDownloads.add(e),i?.read().then(d,c)}addRawSpeed(e,t,i=1,s=!1){if(Ti.sanityCheck(e,t,s)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,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=Zi.get(e);if(P(t))return parseInt(t,10)??void 0}}const Us={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:je.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:Rt.VP9,androidPreferredFormat:wt.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}},Fo=r=>({...Ar(r,Us),configName:[...r.configName??[],...Us.configName]});var Hs=({seekState:r,position$:e})=>O(r.stateChangeEnded$.pipe(A(({to:t})=>t.state===j.None?void 0:(t.position??NaN)/1e3),K(P)),e.pipe(K(()=>r.getState().state===j.None))),Vo=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return w(e,`Wrong container or containerId {${r.container}}`),e};const Uo=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(K(s=>s.length>0),be()).subscribe(s=>{s.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};class bd{subscription=new se;domContainer;providerContainer;chromecastInitializer;logger=new wr;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new de(f.STOPPED),seekState:new de({state:j.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!0),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),internalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({}),cameraOrientation:new de({x:0,y:0})};info={playbackState$:new g(f.STOPPED),position$:new g(0),duration$:new g(1/0),muted$:new g(!1),volume$:new g(1),availableQualities$:new g([]),availableQualitiesFps$:new g({}),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),currentQuality$:new g(void 0),isAutoQualityEnabled$:new g(!0),autoQualityLimitingAvailable$:new g(!1),autoQualityLimits$:new g({}),currentPlaybackRate$:new g(1),currentBuffer$:new g({start:0,end:0}),isBuffering$:new g(!0),isStalled$:new g(!1),isEnded$:new g(!1),isLooped$:new g(!1),isLive$:new g(void 0),canChangePlaybackSpeed$:new g(void 0),atLiveEdge$:new g(void 0),atLiveDurationEdge$:new g(void 0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),currentFormat$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),throughputEstimation$:new g(void 0),rttEstimation$:new g(void 0),videoBitrate$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),surface$:new g(Lt.NONE),chromecastState$:new g(Le.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0),availableSources$:new g(void 0),is3DVideo$:new g(!1)};events={inited$:new I,ready$:new I,started$:new I,playing$:new I,paused$:new I,stopped$:new I,willStart$:new I,willResume$:new I,willPause$:new I,willStop$:new I,willDestruct$:new I,watchCoverageRecord$:new I,watchCoverageLive$:new I,managedError$:new I,fatalError$:new I,ended$:new I,looped$:new I,seeked$:new I,willSeek$:new I,firstBytes$:new I,firstFrame$:new I,canplay$:new I,log$:new I};experimental={element$:new g(void 0),tuningConfigName$:new g([]),enableDebugTelemetry$:new g(!1),dumpTelemetry:Jr};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Fo(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Rr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ti(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const a=Reflect.get(t,i,s);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const c=n.map(u=>JSON.stringify(u,(l,p)=>{const S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),d=`Player.${String(i)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:L.WTF,message:h,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Vo(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Oo({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()===f.STOPPED&&e.startTransitionTo(f.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==f.PLAYING&&t.startTransitionTo(f.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?M(document,"visibilitychange").pipe(be()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==f.PAUSED&&e.startTransitionTo(f.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==f.STOPPED&&e.startTransitionTo(f.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:j.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()===Le.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()===Le.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){w(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(K(i=>i.length>0),be()).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){w(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 Uo(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(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+a.x,y:s.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){w(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(Y(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===j.None?void 0:t.position;return P(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(O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(A(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(K(({from:e})=>e===f.STOPPED),be()).subscribe(()=>{this.initedAt=ne(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case f.READY:this.events.ready$.next();break;case f.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case f.PAUSED:this.events.paused$.next();break;case f.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case f.PAUSED:this.events.willPause$.next();break;case f.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case f.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===j.Requested?this.desiredState.seekState.setState({...n,state:j.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:L.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===j.Applying&&(this.desiredState.seekState.setState({state:j.None}),this.events.seeked$.next())})).add(e.current$.pipe(A(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(A(n=>n.destination),le()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(A(n=>n.map(({quality:o})=>o).sort((o,c)=>Yt(o)?1:Yt(c)?-1:ei(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const c of n)c.fps&&(o[c.quality]=c.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.hostname$.pipe(le()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(le()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(le()).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(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(A(n=>n?{start:n.from,end:n.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(xe({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Hs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(A(({isLive:n,position:o,isLowLatency:c})=>{const d=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),le(),_i(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(xe({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(A(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),le(),_i(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(A(n=>n.muted),le()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(A(n=>n.volume),le()).subscribe(this.info.volume$)).add(Hs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(ti(!0)),e.providerOutput.seekedEvent$.pipe(ti(!1))).pipe(le()).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(A(n=>({id:n?`No${n}`:"NoProviders",category:L.VIDEO_PIPELINE,message:n?`${n} 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(be(),A(n=>n??ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(be(),A(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(be(),A(()=>ne()-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 g(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new g(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(K(({to:n})=>n===f.PLAYING),be()).subscribe(()=>i.next(!1)));let s=0;const a=O(e.providerOutput.isBuffering$,t,i).pipe(A(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),le());this.subscription.add(a.subscribe(n=>{n?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(O(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(O(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let h;d===Le.CONNECTED?h=Lt.SECOND_SCREEN:c?n?h=Lt.PIP:o?h=Lt.FULLSCREEN:h=Lt.INLINE:h=Lt.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(A(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new se;this.subscription.add(t),this.subscription.add(e.current$.pipe(le((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),be()).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=qt(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(O(this.desiredState.videoTrack.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(A(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;w(this.providerContainer),w(e),jr(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Qr(t)),this.providerContainer.current$.subscribe(({type:t})=>Pi("provider",t)),e.duration$.subscribe(t=>Pi("duration",t)),e.availableVideoTracks$.pipe(K(t=>!!t.length),be()).subscribe(t=>Pi("tracks",t)),this.events.fatalError$.subscribe(new ft("fatalError")),this.events.managedError$.subscribe(new ft("managedError")),e.position$.subscribe(new ft("position")),e.currentVideoTrack$.pipe(A(t=>t?.quality)).subscribe(new ft("quality")),this.info.currentBuffer$.subscribe(new ft("buffer")),e.isBuffering$.subscribe(new ft("isBuffering"))].forEach(t=>this.subscription.add(t)),Pi("codecs",Lo())}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:L.DOM,message:String(s)})})};this.subscription.add(O(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===f.PLAYING,n=!!e&&!e?.released;s&&a?n||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 yd=`@vkontakte/videoplayer-core@${xr}`;export{Le as ChromecastState,vi as HttpConnectionType,Ed as Observable,f as PlaybackState,bd as Player,yd as SDK_VERSION,kd as Subject,$d as Subscription,Lt as Surface,xr as VERSION,Ad as ValueSubject,y as VideoFormat,wd as VideoQuality};
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 rr{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 ln(this.params.fov,this.params.orientation),this.cameraRotationManager=new fn(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"),a=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(a,-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(pn,this.gl.VERTEX_SHADER),i=this.createShader(mn,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,a=e-i,n=t-s,o=e+i,c=t-s,d=e+i,h=t+s,u=e-i,l=t+s;return[a,n,o,c,d,h,u,l]}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 ar=class{scene3D;subscription=new se;videoState=new de(me.STOPPED);video;player;params;elementSize$=new m(void 0);textTracksManager=new ot;droppedFramesManager=new wi;videoTracks$=new m([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new qs;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=bt(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(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hn({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=Tt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:x.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=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(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(_t(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Dt(this.video,t.playbackRate,i.playbackRateState$,s)),a(ki(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===me.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Xe.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();D(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,w)=>w.bitrate-b.bitrate),p=Array.from(u.video).sort((b,w)=>w.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const w=nn(b);w&&this.audioTracks.push({track:w,representation:b})}for(const b of p){const w=an(b);if(w){h.push({track:w,representation:b});const C=!this.params.tuning.isAudioDisabled&&on(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const w=dn(b);w&&this.textTracks.push({track:w,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 v=this.selectVideoRepresentation();D(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Xe.REPRESENTATIOS_READY&&(this.videoState.setState(me.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:x.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Xe.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Ie.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Ie.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),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 o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(c.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:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=Ye(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=qt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===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===j.Requested&&i?.to!==f.PAUSED&&e!==me.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==me.STOPPED&&(this.videoState.startTransitionTo(me.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(me.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case me.STOPPED:this.videoState.startTransitionTo(me.READY),this.prepare();return;case me.READY:t===f.PAUSED?(this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case me.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case me.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(me.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===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new rr(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(){Pt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.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),yt(this.video)}},gn=class extends ar{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 Ce;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Ce||(Ce={}));var lt;(function(r){r[r.ActiveLowLatency=0]="ActiveLowLatency",r[r.LiveWithTargetOffset=1]="LiveWithTargetOffset",r[r.LiveForwardBuffering=2]="LiveForwardBuffering",r[r.None=3]="None"})(lt||(lt={}));var Hi;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Hi||(Hi={}));var et;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(et||(et={}));var Q;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(Q||(Q={}));var ai;(function(r){r.MP4="mp4",r.WEBM="webm"})(ai||(ai={}));var Yi;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Yi||(Yi={}));var ge;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ge||(ge={}));let nr=!1;try{nr=Wi().browser===us.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class Sn{bufferFull$=new I;error$=new I;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 a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;nr&&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:x.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:x.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:N(t)}}}class it{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 or extends it{}class bn extends it{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 yn extends it{parseChildrenBoxes(){return Bt(this.content)}}class Tn extends it{parseChildrenBoxes(){return Bt(this.content)}}class vn extends it{data;constructor(e){super(e),this.data=this.content}}class Lt extends it{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class En extends Lt{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,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class kn extends it{parseChildrenBoxes(){return Bt(this.content)}}class $n extends it{parseChildrenBoxes(){return Bt(this.content)}}var Ht;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ht||(Ht={}));class An extends Lt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ht.MONOSCOPIC;break;case 1:this.stereoMode=Ht.TOP_BOTTOM;break;case 2:this.stereoMode=Ht.LEFT_RIGHT;break;case 3:this.stereoMode=Ht.STEREO_CUSTOM;break;case 4:this.stereoMode=Ht.RIGHT_LEFT;break}this.cursor+=1}}class wn extends Lt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Dn extends Lt{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 Pn extends it{parseChildrenBoxes(){return Bt(this.content)}}class Ln extends Lt{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 xn extends it{parseChildrenBoxes(){return Bt(this.content)}}class Rn extends it{parseChildrenBoxes(){return Bt(this.content)}}class In extends Lt{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Cn extends it{parseChildrenBoxes(){return Bt(this.content)}}class _n extends Lt{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 Bn extends Lt{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 Mn extends Lt{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 On={ftyp:bn,moov:yn,moof:Tn,mdat:vn,sidx:En,trak:kn,mdia:Pn,mfhd:In,tkhd:Ln,traf:Cn,tfhd:_n,tfdt:Bn,trun:Mn,minf:xn,sv3d:$n,st3d:An,prhd:wn,proj:Rn,equi:Dn,unknown:or};class Nn{createBox(e,t){const i=On[e];return i?new i(t):new or(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ki.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Ki=new Nn;function Si(r,e){const t=new Uint8Array(r.buffer),i=e.split("").map(n=>n.charCodeAt(0));let s=r.byteOffset,a=[];for(;s<t.byteLength;){if(t[s]===i[a.length]?a.push(t[s]):a=[],a.length===4){const o=new DataView(r.buffer,s-7,4).getUint32(0);return s-7+o>r.buffer.byteLength?null:Ki.createBox(e,new DataView(r.buffer,s-7))}s++}return null}function ns(r,e){const t=[];let i=r.byteOffset;for(;i<r.buffer.byteLength;){const s=Si(new DataView(r.buffer,i,r.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function Bt(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Ki.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Fn=new TextDecoder("ascii"),Vn=r=>Fn.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Un=r=>{const e=Ki.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Q.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Hn=r=>{const e=ns(r,"mdat"),t=ns(r,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],a=i.source.byteOffset,o=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(r.buffer,a,o)},Yn=(r,e)=>{const t=ns(r,"traf"),i=t[t.length-1].children.find(c=>c.type==="tfhd"),s=t[t.length-1].children.find(c=>c.type==="tfdt"),a=t[t.length-1].children.find(c=>c.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((c,d)=>c+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(s.baseMediaDecodeTime)+n)/e*1e3},Gn=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Yi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Si(r,"sv3d")){e.is3dVideo=!0;const i=Si(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=Si(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=Si(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},zn={validateData:Vn,parseInit:Gn,getIndexRange:()=>{},parseSegments:Un,parseFeedableSegmentChunk:Hn,getSegmentEndTime:Yn};var $;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})($||($={}));var B;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(B||(B={}));const ws={[$.EBML]:{type:B.Master},[$.EBMLVersion]:{type:B.UnsignedInteger},[$.EBMLReadVersion]:{type:B.UnsignedInteger},[$.EBMLMaxIDLength]:{type:B.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:B.UnsignedInteger},[$.DocType]:{type:B.String},[$.DocTypeVersion]:{type:B.UnsignedInteger},[$.DocTypeReadVersion]:{type:B.UnsignedInteger},[$.Void]:{type:B.Binary},[$.Segment]:{type:B.Master},[$.SeekHead]:{type:B.Master},[$.Seek]:{type:B.Master},[$.SeekID]:{type:B.Binary},[$.SeekPosition]:{type:B.UnsignedInteger},[$.Info]:{type:B.Master},[$.TimestampScale]:{type:B.UnsignedInteger},[$.Duration]:{type:B.Float},[$.Tracks]:{type:B.Master},[$.TrackEntry]:{type:B.Master},[$.Video]:{type:B.Master},[$.Projection]:{type:B.Master},[$.ProjectionType]:{type:B.UnsignedInteger},[$.ProjectionPrivate]:{type:B.Master},[$.Chapters]:{type:B.Master},[$.Cluster]:{type:B.Master},[$.Timestamp]:{type:B.UnsignedInteger},[$.SilentTracks]:{type:B.Master},[$.SilentTrackNumber]:{type:B.UnsignedInteger},[$.Position]:{type:B.UnsignedInteger},[$.PrevSize]:{type:B.UnsignedInteger},[$.SimpleBlock]:{type:B.Binary},[$.BlockGroup]:{type:B.Master},[$.EncryptedBlock]:{type:B.Binary},[$.Attachments]:{type:B.Master},[$.Tags]:{type:B.Master},[$.Cues]:{type:B.Master},[$.CuePoint]:{type:B.Master},[$.CueTime]:{type:B.UnsignedInteger},[$.CueTrackPositions]:{type:B.Master},[$.CueTrack]:{type:B.UnsignedInteger},[$.CueClusterPosition]:{type:B.UnsignedInteger},[$.CueRelativePosition]:{type:B.UnsignedInteger},[$.CueDuration]:{type:B.UnsignedInteger},[$.CueBlockNumber]:{type:B.UnsignedInteger},[$.CueCodecState]:{type:B.UnsignedInteger},[$.CueReference]:{type:B.Master},[$.CueRefTime]:{type:B.UnsignedInteger}},dr=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Gi(r,t),s=i in ws,a=s?ws[i].type:B.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Gi(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Gi=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},mt=(r,e)=>{switch(e){case B.SignedInteger:return r.getInt8(0);case B.UnsignedInteger:return Gi(r);case B.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case B.String:return new TextDecoder("ascii").decode(r);case B.UTF8:return new TextDecoder("utf-8").decode(r);case B.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case B.Master:return r;case B.Binary:return r;default:N(e)}},ni=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=dr(i);if(!e(s))return;s.type===B.Master&&ni(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},qn=r=>{if(r.getUint32(0)!==$.EBML)return!1;let e,t,i;const s=dr(r);return ni(s.value,({tag:a,type:n,value:o})=>(a===$.EBMLReadVersion?e=mt(o,n):a===$.DocType?t=mt(o,n):a===$.DocTypeReadVersion&&(i=mt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},cr=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],Wn=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],Qn=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ni(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===$.SeekID){const b=mt(S,p);d=Gi(b)}else l!==$.SeekPosition&&(d=void 0);return l===$.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===$.Info?a=!0:l===$.SeekHead?n=!0:l===$.TimestampScale?i=mt(S,p):l===$.Duration?s=mt(S,p):l===$.SeekPosition&&d===$.Cues?c=mt(S,p):l===$.Tracks?ni(S,({tag:b,type:w,value:C})=>b===$.ProjectionType?(h=mt(C,w)===1,!1):!0):a&&n&&cr.includes(l)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(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:c,is3dVideo:h,stereoMode:u,projectionType:Yi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},jn=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Jn=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ni(r,({tag:o,type:c,value:d})=>{switch(o){case $.Cues:t=!0;break;case $.CuePoint:n&&s(n)&&a.push(n),n={};break;case $.CueTime:n&&(n.time=mt(d,c));break;case $.CueTrackPositions:break;case $.CueClusterPosition:n&&(n.position=mt(d,c));break;default:t&&cr.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:Q.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Xn=r=>{let e=0,t=!1;try{ni(r,i=>i.tag===$.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Wn.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Kn={validateData:qn,parseInit:Qn,getIndexRange:jn,parseSegments:Jn,parseFeedableSegmentChunk:Xn},Ds=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Xt=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},Zn=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=Ds(l);else if(p){const g=Ds(p);P(g)&&(u=g)}else v&&(u=parseInt(v,10));let b=0;const w=a.getAttribute("profiles")?.split(",")??[],C=w.includes(Hi.WEBM_AS_IN_FFMPEG)||w.includes(Hi.WEBM_AS_IN_SPEC)?ai.WEBM:ai.MP4;for(const g of o){const E=g.getAttribute("mimeType"),L=g.getAttribute("codecs"),H=g.getAttribute("contentType")??E?.split("/")[0],q=g.getAttribute("profiles")?.split(",")??[],F=g.querySelectorAll("Representation"),G=g.querySelector("SegmentTemplate");if(H===Ce.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=g.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Ce.TEXT].push({id:V,lang:z,isAuto:ke,kind:Ce.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??E,z=T.getAttribute("codecs")??L??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=g.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,_e=pe?ji(pe):void 0,dt=T.getAttribute("id")??(b++).toString(10),ci=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,Wt=`${dt}@${ci}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Ve=[...w,...q,...ye];let De;const Et=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(Et){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,ct]=Ae.split("-").map(ze=>parseInt(ze,10)),Ue={from:Pe,to:ct},st=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[Mt,kt]=st?st.split("-").map(ze=>parseInt(ze,10)):[],rt=st?{from:Mt,to:kt}:void 0;De={type:et.BYTE_RANGE,url:we,initRange:Ue,indexRange:rt}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),ct=Te.getAttribute("initialization")??"",Ue=Te.getAttribute("media"),st=parseInt(Te.getAttribute("startNumber")??"",10)??1,Mt=Xt(ct,Ae);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const kt=Te.querySelectorAll("SegmentTimeline S")??[],rt=[];let ze=0,Ot="",qe=0;if(kt.length){let We=st,ve=0;for(const at of kt){const He=parseInt(at.getAttribute("d")??"",10),ut=parseInt(at.getAttribute("r")??"",10)||0,$t=parseInt(at.getAttribute("t")??"",10);ve=Number.isFinite($t)?$t:ve;const ui=He/Pe*1e3,Pi=ve/Pe*1e3;for(let Qt=0;Qt<ut+1;Qt++){const gr=Xt(Ue,{...Ae,segmentNumber:We.toString(10),segmentTime:(ve+Qt*He).toString(10)}),ms=(Pi??0)+Qt*ui,Sr=ms+ui;We++,rt.push({time:{from:ms,to:Sr},url:gr})}ve+=(ut+1)*He,ze+=(ut+1)*ui}qe=ve/Pe*1e3,Ot=Xt(Ue,{...Ae,segmentNumber:We.toString(10),segmentTime:ve.toString(10)})}else if(P(u)){const ve=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,at=Math.ceil(u/ve);let He=0;for(let ut=1;ut<at;ut++){const $t=Xt(Ue,{...Ae,segmentNumber:ut.toString(10),segmentTime:He.toString(10)});rt.push({time:{from:He,to:He+ve},url:$t}),He+=ve}qe=He,Ot=Xt(Ue,{...Ae,segmentNumber:at.toString(10),segmentTime:He.toString(10)})}const Nt={time:{from:qe,to:1/0},url:Ot};De={type:et.TEMPLATE,baseUrl:we,segmentTemplateUrl:Ue,initUrl:Mt,totalSegmentsDurationMs:ze,segments:rt,nextSegmentBeyondManifest:Nt,timescale:Pe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ge={video:Ce.VIDEO,audio:Ce.AUDIO,text:Ce.TEXT}[te];Ge&&s[Ge].push({id:Wt,kind:Ge,segmentReference:De,profiles:Ve,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:_e,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},eo=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?oi(a):void 0)??Ct({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},to=({id:r,bitrate:e})=>({id:r,bitrate:e}),io=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},so=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),Ps=r=>"size"in r,jt=r=>r.type===et.TEMPLATE,os=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);class Ls{onLastSegment$=new m(!1);fullyBuffered$=new m(!1);playingRepresentation$=new m(void 0);playingRepresentationInit$=new m(void 0);error$=new I;gaps=[];subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new tt;destroyAbortController=new tt;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:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:c,compatibilityMode:d=!1,manifest:h}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=c,this.isLive=!!h?.dynamic,this.container=i,i){case ai.MP4:this.containerParser=zn;break;case ai.WEBM:this.containerParser=Kn;break;default:N(i)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);D(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Sn(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:x.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Vi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);D(i,"No init buffer for starting representation"),D(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(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);D(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),D(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 a=this.getCurrentPosition();P(a)&&(this.isLive||(i.forEach(n=>n.status=Q.NONE),this.pruneBuffer(a,1/0,!0)),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Ye(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Vi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Ye(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===Q.FED&&!o.length&&Ye(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=i.at(-1);c&&c.status===Q.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+s}),i=a.time.to;P(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 a=0,n=t.length-1;do s.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-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=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d||!jt(d.segmentReference))return;const h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);D(i);const s=this.segments.get(t);D(s,"No segments for starting representation");const a=this.initData.get(t);if(D(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!jt(t.segmentReference))return;const i=t.segmentReference.segments.map(o=>({...o,status:Q.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.floor(a)>=Math.floor(o.time.from)&&Math.floor(a)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!jt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),a=Xt(i.segmentTemplateUrl,{segmentTime:s}),n=this.segments.get(t.id)??[],o=n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||n.push({status:Q.NONE,time:{from:e.segment.time.to,to:1/0},url:a})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.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:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,w=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+w||p<=i+w;return(u===Q.NONE||u===Q.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!si(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==et.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===Q.NONE||l.status===Q.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){t.segmentReference.type===et.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Q.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:a,url:n,signal:o,onProgress:c,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await oe(o,async function*(){const h=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,h))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:c,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const u=new DataView(h);if(this.isActiveLowLatency()){const l=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(u,l)}c&&s.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(u,o),s.segment.status=Q.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!os(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const c of e)c.status=Q.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await oe(n,async function*(){const c=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:s,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(c){if(!os(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}}prepareByteRangeFetchSegmentParams(e,t){if(jt(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:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:s,signal:a,onProgress:(c,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:x.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!jt(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:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,u)=>{if(!a.aborted)try{const l=this.onSomeTemplateDataLoaded({dataView:h,loaded:u,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:x.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:s,signal:a,onProgress:d,onProgressTasks:o}}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&&P(i)&&(t=Ye(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:x.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:c}=o;if(o.representationId===t){if(a.aborted){s();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(d);h?.byteLength&&(c.status=Q.PARTIALLY_FED,o.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),o.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const c=o.segmentReference.type,d=e.byteLength;for(const h of this.activeSegments){const{segment:u}=h,l=c===et.BYTE_RANGE,p=l?u.byte.to-u.byte.from+1:d;if(h.representationId!==t||!(!l||u.byte.from>=i&&u.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const v=l?u.byte.from-i:0,b=l?u.byte.to-i:e.byteLength,w=v<s,C=b<=s;if(u.status===Q.DOWNLOADING&&w&&C){u.status=Q.DOWNLOADED;const g=new DataView(e.buffer,e.byteOffset+v,p);this.sourceBufferTaskQueue.append(g,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(h,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&w&&(h.loadedBytes=Math.min(p,s-v),h.loadedBytes>h.feedingBytes)){const g=new DataView(e.buffer,e.byteOffset+v+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===p?g:this.containerParser.parseFeedableSegmentChunk(g);E?.byteLength&&(u.status=Q.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then(L=>{if(a.aborted)n();else if(L)h.fedBytes+=E.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Q.FED,Ps(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===Q.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=Q.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.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,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Fi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=bi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:c,dataView:d,segments:h}=o,u=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,u);let l=h;this.isLive&&jt(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h=Ps(d)?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===Q.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===Q.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===Q.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===Q.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!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 a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Fi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:x.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(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),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==Q.FED&&a!==Q.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=Q.PARTIALLY_EJECTED:s.status=Q.NONE)}}}var Zt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Zt||(Zt={}));class ro{throughputEstimator;requestQuic;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);abortAllController=new tt;subscription=new se;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}=fs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=It(t));const i=yield zt(t,{signal:this.abortAllController.signal}).catch(fi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Zt.HEADER:Zt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let d=e;const h=new Headers;if(i)switch(t){case Zt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Zt.PARAM:{const F=new URL(d,location.href);F.searchParams.append("bytes",`${i.from}-${i.to}`),d=F.toString();break}default:N(t)}this.requestQuic&&(d=It(d));let u=this.abortAllController.signal,l;if(n){const F=new tt;if(l=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{F.abort()}catch(G){fi(G)}}),this.abortAllController.signal.aborted||n.aborted)try{F.abort()}catch(G){fi(G)}u=F.signal}const p=ne(),S=yield zt(d,{priority:a,headers:h,signal:u}).catch(fi),v=ne();if(!S)return l?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-p),!S.ok||!S.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));if(this.onHeadersReceived(S.headers),!s&&!o)return l?.unsubscribe(),S.arrayBuffer();const[b,w]=S.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(w,c);let g=0,E=new Uint8Array(0),L=!1;const H=F=>{l?.unsubscribe(),L=!0,fi(F)},q=oe(u,async function*({done:F,value:G}){if(g===0&&this.lastRequestFirstBytes$.next(ne()-p),u.aborted){l?.unsubscribe();return}if(!F&&G){const T=new Uint8Array(E.length+G.length);T.set(E),T.set(G,E.length),E=T,g+=G.byteLength,s?.(new DataView(E.buffer),g),yield C?.read().then(q,H)}}.bind(this));return yield C?.read().then(q,H),l?.unsubscribe(),L?null:E.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case et.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case et.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==et.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const w=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!w)return null;v=new DataView(w)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==et.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(n=>({...n,status:Q.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const fi=r=>{if(!os(r))throw r},ds=1e3,zi=(r,e,t)=>t*e+(1-t)*r,ur=(r,e)=>r.reduce((t,i)=>t+i,0)/e,ao=(r,e,t,i)=>{let s=0,a=t;const n=ur(r,e),o=e<i?e:i;for(let c=0;c<o;c++)r[a]>n?s++:s--,a=(r.length+a-1)%r.length;return Math.abs(s)===o};class ps{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 m(e.initial),this.debounced$=new m(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ft(`raw_${t}`),this.smoothedSeries$=new ft(`smoothed_${t}`),this.reportedSeries$=new ft(`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 o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*s,n=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>a||this.smoothed<n)&&(Y(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 no extends ps{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=zi(this.slow,e,this.params.emaAlphaSlow),this.fast=zi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class oo extends ps{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ur(this.pastMeasures,this.takenMeasures);this.emaSmoothed=zi(this.emaSmoothed,e,this.params.emaAlpha);const i=ao(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class co extends ps{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?zi(this.smoothed,e,this.params.emaAlpha):e}}class cs{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new no({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new oo({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 co({initial:e,label:"liveEdgeDelay",...t})}}const uo=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)},xs=["timeupdate","progress","play","seeked","stalled","waiting"];var Ke;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Ke||(Ke={}));let ho=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Ke.NONE);currentVideoRepresentation$=new m(void 0);currentVideoRepresentationInit$=new m(void 0);error$=new I;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);isLive$=new m(!1);liveDuration$=new m(0);liveAvailabilityStartTime$=new m(void 0);bufferLength$=new m(0);liveLoadBufferLength$=new m(0);livePositionFromPlayer$=new m(0);liveEstimatedDelay;waitingEventInterval;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new tt;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ro({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=cs.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Oe(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ke.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Ke.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:x.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(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:x.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Zn(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:x.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Ce.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,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){D(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Oe(this.manifestUrlString,t,fe.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=oe(this.destroyController.signal,async function*(e,t){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ke.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 Ls(Ce.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new Ls(Ce.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(Gt(ds).subscribe(n=>{if(this.element?.paused){const o=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Oe(this.manifestUrlString,o+ds,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...xs.map(n=>M(this.element,n))).pipe(A(n=>this.element?Ye(this.element.buffered,this.element.currentTime*1e3):0),le(),K(n=>!!n),vi(n=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(K(o=>this.isActiveLowLatency&&!!o)).subscribe(o=>this.liveEstimatedDelay.next(o))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(o=>{if(!this.isActiveLowLatency)return;const c=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,d=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=o-c;let l=1+Math.sign(u)*h;Math.abs(u)<d?l=1:Math.abs(u)>d*2&&(l=1+Math.sign(u)*h*2),uo(this.element,l)})),this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(Le({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:o,bufferLength:c})=>{if(D(this.element),this.isUpdatingLive)return;const d=this.element.playbackRate,h=Bi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,l=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*d),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*d,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*d,v=this.isActiveLowLatency?c:o;let b=lt.None;if(this.isActiveLowLatency?b=lt.ActiveLowLatency:v<l+S&&v>=l?b=lt.LiveWithTargetOffset:h!==0&&v<l&&(b=lt.LiveForwardBuffering),isFinite(o)&&(n=o>n?o:n),b===lt.LiveForwardBuffering||b===lt.LiveWithTargetOffset){const w=n-(l+p),C=this.normolizeLiveOffset(Math.trunc(h+w/d)),g=Math.abs(C-h);let E;!o||g<=this.tuning.dashCmafLive.offsetCalculationError?E=h:C>0&&g>this.tuning.dashCmafLive.offsetCalculationError?E=C:E=0,this.manifestUrlString=Oe(this.manifestUrlString,E,fe.DASH_CMAF_OFFSET_P)}b!==lt.None&&b!==lt.ActiveLowLatency&&(n=0,this.updateLive())}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,Le({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:x.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.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(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Ke.REPRESENTATIOS_READY)}.bind(this));initBuffer(){D(this.element),this.state$.setState(Ke.RUNNING),this.subscription.add(O(...xs.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:x.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&si(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{[Ce.VIDEO]:this.videoBufferManager,[Ce.AUDIO]:this.audioBufferManager,[Ce.TEXT]:null}[e]?.switchTo(t)}seek(e,t){D(this.element),D(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),si(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(Ke.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:x.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=Gt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:x.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 a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.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 hr{scene3D;subscription=new se;videoState=new de(ge.STOPPED);video;player;params;elementSize$=new m(void 0);textTracksManager=new ot;droppedFramesManager=new wi;videoTracks$=new m([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new qs;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=bt(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(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ho({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=Tt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:x.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=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(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(_t(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Dt(this.video,t.playbackRate,i.playbackRateState$,s)),a(ki(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Ke.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();D(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,w)=>w.bitrate-b.bitrate),p=Array.from(u.video).sort((b,w)=>w.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const w=to(b);w&&this.audioTracks.push({track:w,representation:b})}for(const b of p){const w=eo(b);if(w){h.push({track:w,representation:b});const C=!this.params.tuning.isAudioDisabled&&io(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const w=so(b);w&&this.textTracks.push({track:w,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 v=this.selectVideoRepresentation();D(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Ke.REPRESENTATIOS_READY&&(this.videoState.setState(ge.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:x.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Ke.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Ce.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Ce.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),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 o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(c.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:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=Ye(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=qt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===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===j.Requested&&i?.to!==f.PAUSED&&e!==ge.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.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(ge.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case ge.STOPPED:this.videoState.startTransitionTo(ge.READY),this.prepare();return;case ge.READY:t===f.PAUSED?(this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case ge.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ge.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ge.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===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new rr(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(){Pt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.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),yt(this.video)}}class lo extends hr{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 fo=class extends ar{constructor(e){super(e),this.liveOffset=new Ai}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(Le({interval:Gt(as),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===me.PLAYING){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(Le({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a: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===f.PAUSED&&i===me.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}};class po extends hr{constructor(e){super(e),this.liveOffset=new Ai}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(Le({interval:Gt(ds),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ge.PLAYING&&!this.player.isActiveLowLatency){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(Le({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a: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===f.PAUSED&&i===ge.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const ht={};var ie;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ie||(ie={}));const pi=(r,e)=>new Qi(t=>{const i=(s,a)=>t.next(a);return r.on(e,i),()=>r.off(e,i)});class mo{subscription=new se;videoState=new de(ie.INITIALIZING);video;params;hls;textTracksManager=new ot;trackLevels=new Map;constructor(e){this.video=bt(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(Fe(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),yt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:x.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||(ht.Hls=s.default,ht.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){D(ht.Hls,"hls.js not loaded"),this.hls=new ht.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ie.STOPPED)}subscribe(){D(ht.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:x.WTF,message:"HlsJsProvider internal logic error",thrown:d})},s=Tt(this.video),a=(d,h)=>this.subscription.add(d.subscribe(h,i));a(s.timeUpdate$,t.position$),a(s.durationChange$,t.duration$),a(s.ended$,t.endedEvent$),a(s.looped$,t.loopedEvent$),a(s.error$,t.error$),a(s.isBuffering$,t.isBuffering$),a(s.currentBuffer$,t.currentBuffer$),a(s.loadStart$,t.firstBytesEvent$),a(s.playing$,t.firstFrameEvent$),a(s.canplay$,t.canplay$),a(s.seeked$,t.seekedEvent$),a(s.inPiP$,t.inPiP$),a(s.inFullscreen$,t.inFullscreen$),this.subscription.add(_t(this.video,e.isLooped,i)),this.subscription.add(St(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(pi(this.hls,ht.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:x.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),R(e.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),R(e.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),a(pi(this.hls,ht.Events.MANIFEST_PARSED).pipe(A(({levels:d})=>d.reduce((h,u)=>{const l=u.name||u.height.toString(10),{width:p,height:S}=u,v=oi(u.attrs.QUALITY??"")??Ct({width:p,height:S});if(!v)return h;const b=u.attrs["FRAME-RATE"]?parseFloat(u.attrs["FRAME-RATE"]):void 0,w={id:l.toString(),quality:v,bitrate:u.bitrate/1e3,size:{width:p,height:S},fps:b};return this.trackLevels.set(l,{track:w,level:u}),h.push(w),h},[]))),t.availableVideoTracks$),a(pi(this.hls,ht.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const h=[];for(const u of d.subtitleTracks){const l=u.name,p=u.attrs.URI||"",S=u.lang,v="internal";h.push({id:l,url:p,language:S,type:v})}e.internalTextTracks.startTransitionTo(h)}}),a(pi(this.hls,ht.Events.LEVEL_LOADING).pipe(A(({url:d})=>Fe(d))),t.hostname$),this.subscription.add(nt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>Array.from(this.trackLevels.values()).find(({level:h})=>h===d)?.track,o=pi(this.hls,ht.Events.LEVEL_SWITCHED).pipe(A(({level:d})=>n(this.hls.levels[d])));o.pipe(K(P)).subscribe(t.currentVideoTrack$,i),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{if(Y(d))return;const h=this.trackLevels.get(d.id)?.level;if(!h)return;const u=this.hls.levels.indexOf(h),l=this.hls.currentLevel,p=this.hls.levels[l];!p||h.bitrate>p.bitrate?this.hls.nextLevel=u:(this.hls.loadLevel=u,this.hls.loadLevel=u)},{changed$:o,onError:i})),a(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(c.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!==ie.INITIALIZING)switch(i?.to!==f.PAUSED&&s.state===j.Requested&&this.seek(s.position),t){case f.STOPPED:switch(e){case ie.STOPPED:break;case ie.READY:case ie.PLAYING:case ie.PAUSED:this.stop();break;default:N(e)}break;case f.READY:switch(e){case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PLAYING:case ie.PAUSED:break;default:N(e)}break;case f.PLAYING:switch(e){case ie.PLAYING:break;case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PAUSED:this.playIfAllowed();break;default:N(e)}break;case f.PAUSED:switch(e){case ie.PAUSED:break;case ie.STOPPED:this.prepare();break;case ie.READY:this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case ie.PLAYING:this.pause();break;default:N(e)}break;default:N(t)}};prepare(){this.videoState.startTransitionTo(ie.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ie.PLAYING),await Pt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.DOM,thrown:t}))||(this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ie.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(ie.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}}const Rs="X-Playback-Duration";var Is=async r=>{const e=await zt(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Rs)?parseInt(e.headers.get(Rs),10):void 0};const go=r=>{let e=null;if(r.QUALITY&&(e=oi(r.QUALITY)),!e&&r.RESOLUTION){const[t,i]=r.RESOLUTION.split("x").map(s=>parseInt(s,10));e=Ct({width:t,height:i})}return e??null},lr=async(r,e=r)=>{const s=(await(await zt(r)).text()).split(`
46
+ `),a=[],n=[];for(let o=0;o<s.length;o++){const c=s[o],d=c.match(/^#EXT-X-STREAM-INF:(.+)/),h=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!h)){if(d){const u=Object.fromEntries(d[1].split(",").map(C=>C.split("="))),l=u.QUALITY??`stream-${u.BANDWIDTH}`,p=go(u);let S;u.BANDWIDTH&&(S=parseInt(u.BANDWIDTH,10)/1e3||void 0),!S&&u["AVERAGE-BANDWIDTH"]&&(S=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let b;if(u.RESOLUTION){const[C,g]=u.RESOLUTION.split("x").map(E=>parseInt(E,10));C&&g&&(b={width:C,height:g})}const w=new URL(s[++o],e).toString();p&&a.push({id:l,quality:p,url:w,bandwidth:S,size:b,fps:v})}if(h){const u=Object.fromEntries(h[1].split(",").map(v=>v.split("=")).map(([v,b])=>[v,b.replace(/^"|"$/g,"")])),l=u.URI?.replace(/playlist$/,"subtitles.vtt"),p=u.LANGUAGE,S=u.NAME;l&&p&&n.push({type:"internal",id:p,label:S,language:p,url:l,isAuto:!1})}}}return{qualityManifests:a,textTracks:n}};var ce;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(ce||(ce={}));class So{subscription=new se;videoState=new de(ce.STOPPED);video;params;textTracksManager=new ot;masterManifest;manifests$=new m([]);maxSeekBackTime$;liveOffset=new Ai;manifestStartTime$=new m(void 0);constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Je.INVARIANT,url:this.params.source.url},lr(Oe(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:x.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:x.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(Fe(this.params.source.url)),this.maxSeekBackTime$=new m(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:x.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=Tt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.ended$,e.endedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(St(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(le(),A(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Fe(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===ce.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===j.Requested&&this.seek(o.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Le({startTime:this.manifestStartTime$.pipe(K(P)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),i)),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),yt(this.video)}prepare(){const e=this.selectManifest();if(Y(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:o,min:c}=t?.to??i??{};for(const[d,h]of[[o,"mq"],[c,"lq"]]){const u=String(parseFloat(d||""));h&&d&&s.searchParams.set(h,u)}}const a=this.params.format===y.HLS_LIVE_CMAF?fe.DASH_CMAF_OFFSET_P:fe.OFFSET_P,n=Oe(s.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",n),this.video.load(),Is(n).then(o=>{if(!Y(o))this.maxSeekBackTime$.next(o);else{const c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Y(c)||!isFinite(c))try{zt(n).then(d=>d.text()).then(d=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(h){const u=new URL(h,n).toString();Is(u).then(l=>{Y(l)||this.maxSeekBackTime$.next(l)})}})}catch{}}})}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.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(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.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(ce.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(ce.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==f.PAUSED&&d.state===j.Requested){this.videoState.startTransitionTo(ce.READY),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case ce.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ce.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(ce.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===f.PAUSED&&(R(this.params.desiredState.playbackState,f.PAUSED),this.liveOffset.pause());return;case ce.CHANGING_MANIFEST:break;default:return N(t)}}}var he;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(he||(he={}));class bo{subscription=new se;videoState=new de(he.STOPPED);video;params;textTracksManager=new ot;masterManifest;manifests$=new m([]);constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Je.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(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),lr(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:x.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(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:x.WTF,message:"HlsProvider internal logic error",thrown:o})},s=Tt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c));if(a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(St(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===he.READY&&this.videoState.setState(he.READY),this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Fe(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===he.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===j.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i)),!$r()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(O(M(o,"addtrack"),M(o,"removetrack"),M(o,"change"),Ne(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},i))}const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),yt(this.video)}prepare(){const e=this.selectManifest();if(Y(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:a,min:n}=t?.to??i??{};for(const[o,c]of[[a,"mq"],[n,"lq"]]){const d=String(parseFloat(o||""));c&&o&&s.searchParams.set(c,d)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.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(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.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(he.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===he.STOPPED){this.videoState.startTransitionTo(he.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(he.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:u}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:u*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&d.state===j.Requested&&this.seek(d.position),t){case he.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed());return;case he.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case he.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;case he.CHANGING_MANIFEST:break;default:return N(t)}}}var Se;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Se||(Se={}));class yo{subscription=new se;videoState=new de(Se.STOPPED);video;trackUrls={};params;textTracksManager=new ot;constructor(e){this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const a=s.toString(10);this.trackUrls[a]={track:{quality:t,id:a},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=o=>{e.error$.next({id:"MpegProvider",category:x.WTF,message:"MpegProvider internal logic error",thrown:o})},s=Tt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(_t(this.video,t.isLooped,i)),this.subscription.add(St(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Dt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Se.READY&&this.videoState.setState(Se.READY);const o=this.params.desiredState.videoTrack.getTransition();o&&P(o.to)&&(this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track)),this.videoState.getState()===Se.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),yt(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;D(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];D(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=It(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Fe(t))}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.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===f.STOPPED){e!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.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(Se.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!==Se.READY&&!n){this.handleQualityLimitTransition(a.to.max);return}if(e===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){const{currentTime:c}=this.video;this.prepare(),o.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==f.PAUSED&&o.state===j.Requested&&this.seek(o.position),e){case Se.READY:t===f.READY?R(this.params.desiredState.playbackState,f.READY):t===f.PAUSED?(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Se.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(o=>!Yt(o.track.quality)&&Ys(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[a??"0"]?.track;if(s&&n&&is(n.quality,s.quality)&&(t=s),!t){const o=Object.values(this.trackUrls).filter(d=>!Yt(d.track.quality)&&ei(d.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(a=>a.track);t=qt(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 Cs=["stun:videostun.mycdn.me:80"],To=1e3,vo=3,ts=()=>null;class Eo{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=ts;externalStopCallback=ts;externalErrorCallback=ts;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:Cs}]};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:x.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),To)}normalizeOptions(e={}){const t={stunServerList:Cs,maxRetryNumber:vo,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ue;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ue||(ue={}));class ko{subscription;params;log;video;videoState=new de(ue.STOPPED);liveStreamClient;maxSeekBackTime$=new m(0);constructor(e){this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=bt(e.container),this.liveStreamClient=new Eo(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),yt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:x.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(this.videoState.stateChangeStarted$.pipe(A(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=Tt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(s.timeUpdate$,e.liveTime$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ue.READY&&this.videoState.setState(ue.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(St(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ue.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(f.STOPPED);break;case ue.READY:break;case ue.PAUSED:t.playbackState.setState(f.PAUSED);break;case ue.PLAYING:t.playbackState.setState(f.PLAYING);break;default:return N(n.to)}},i)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(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(Fe(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:Je.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,f.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ue.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:x.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Pt(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:x.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===f.STOPPED){e!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.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(ue.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===ue.STOPPED){this.videoState.startTransitionTo(ue.READY),this.prepare();return}if(a){this.prepare();return}switch(e){case ue.READY:t===f.PAUSED?(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed());return;case ue.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ue.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}class _s{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 fr=Wi().device===Ar.Android,qi=document.createElement("video"),$o='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ao='video/mp4; codecs="hev1.1.6.L93.B0"',pr='video/webm; codecs="vp09.00.10.08"',mr='video/webm; codecs="av01.0.00M.08"',wo='audio/mp4; codecs="mp4a.40.2"',Do='audio/webm; codecs="opus"',xe={mms:!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(qi.canPlayType?.("application/x-mpegurl")||qi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Qe={mp4:!!qi.canPlayType?.("video/mp4"),webm:!!qi.canPlayType?.("video/webm"),cmaf:!0},gt={h264:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.($o),h265:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Ao),vp9:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(pr),av1:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(mr),aac:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(wo),opus:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Do)},Jt=(gt.h264||gt.h265)&&gt.aac;var Rt;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Rt||(Rt={}));var wt;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(wt||(wt={}));let Ft;const Po=async()=>{if(!window.navigator.mediaCapabilities)return;const r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:mr}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:pr}})]);Ft={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{Po()}catch(r){console.error(r)}const $i=xe.hls&&Qe.mp4,Lo=()=>Object.keys(gt).filter(r=>gt[r]),xo=(r,e=!1,t=!1)=>r.filter(i=>{switch(i){case y.DASH:return xe.mse&&Qe.mp4&&Jt;case y.DASH_SEP:return(xe.mse||xe.mms&&t)&&Qe.mp4&&Jt;case y.DASH_WEBM:return(xe.mse||xe.mms&&t)&&Qe.webm&&gt.vp9&&gt.opus;case y.DASH_WEBM_AV1:return(xe.mse||xe.mms&&t)&&Qe.webm&&gt.av1&&gt.opus;case y.DASH_LIVE:return xe.mse&&Qe.mp4&&Jt;case y.DASH_LIVE_CMAF:return(xe.mse||xe.mms&&t)&&Qe.mp4&&Jt&&Qe.cmaf;case y.DASH_ONDEMAND:return(xe.mse||xe.mms&&t)&&Qe.mp4&&Jt;case y.HLS:case y.HLS_ONDEMAND:return $i||e&&xe.mse&&Qe.mp4&&Jt;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return $i;case y.MPEG:return Qe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return xe.webrtc&&xe.ws&&gt.h264&&(Qe.mp4||Qe.webm);default:return N(i)}}),mi=r=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(r){case Rt.VP9:return[e,t];case Rt.AV1:return[t,e];case Rt.NONE:return[];case Rt.SMOOTH:return Ft?Ft[t].smooth?[t,e]:Ft[e].smooth?[e,t]:[t,e]:[e,t];case Rt.POWER_EFFICIENT:return Ft?Ft[t].powerEfficient?[t,e]:Ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:N(r)}return[e,t]},Ro=({webmCodec:r,androidPreferredFormat:e})=>{if(fr)switch(e){case wt.MPEG:return[y.MPEG,...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case wt.HLS:return[y.HLS,y.HLS_ONDEMAND,...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case wt.DASH:return[...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return $i?[...mi(r),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...mi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},Io=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],s=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...s],n=[...s,...i];let o;if(fr)switch(r){case wt.DASH:{o=a;break}case wt.HLS:case wt.MPEG:{o=n;break}}else $i?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Bs=r=>r?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var Co=r=>new Qi(e=>{const t=new se,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(A(({from:d,to:h})=>`${d}-${h}`)),s=r.desiredPlaybackState$.stateChangeEnded$,a=r.providerChanged$.pipe(A(({type:d})=>d!==void 0)),n=new I;let o=0,c="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),r.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(c),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const _o={cacheDuration:12e4},Bo={chunkDuration:5e3,maxParallelRequests:5};class Mo{current$=new m({type:void 0});providerError$=new I;noAvailableProvidersError$=new I;providerOutput={position$:new m(0),duration$:new m(1/0),volume$:new m({muted:!1,volume:1}),currentVideoTrack$:new m(void 0),availableVideoTracks$:new m([]),availableAudioTracks$:new m([]),isAudioAvailable$:new m(!0),autoVideoTrackLimitingAvailable$:new m(!1),autoVideoTrackLimits$:new m(void 0),currentBuffer$:new m(void 0),isBuffering$:new m(!0),error$:new I,warning$:new I,willSeekEvent$:new I,seekedEvent$:new I,loopedEvent$:new I,endedEvent$:new I,firstBytesEvent$:new I,firstFrameEvent$:new I,canplay$:new I,isLive$:new m(void 0),isLowLatency$:new m(!1),canChangePlaybackSpeed$:new m(!0),liveTime$:new m(void 0),liveBufferTime$:new m(void 0),availableTextTracks$:new m([]),currentTextTrack$:new m(void 0),hostname$:new m(void 0),httpConnectionType$:new m(void 0),httpConnectionReused$:new m(void 0),inPiP$:new m(!1),inFullscreen$:new m(!1),element$:new m(void 0),availableSources$:new m(void 0),is3DVideo$:new m(!1)};subscription=new se;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=xo([...Io(this.params.tuning),...Ro(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>P(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let a=[];i?a=[i]:s.length?a=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new _s(a),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(a);const n=[...Bs(!0),...Bs(!1)];this.chromecastFormatsIterator=new _s(n.filter(o=>P(e.sources[o]))),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),Y(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:x.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!==j.None;if(this.params.desiredState.seekState.setState({state:j.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Be.SCREEN:return this.createScreenProvider(t);case Be.CHROMECAST:return this.createChromecastProvider(t);default:return N(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return D(o),new Ta({...n,source:o,config:_o})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJs?new bs({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new lo({...n,source:o})):new gn({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJsCMAF?new bs({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new po({...n,source:o}):new fo({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),$i||!this.params.tuning.useHlsJs?new bo({...n,source:o}):new mo({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new So({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return D(o),new yo({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new ma({...n,source:o,config:{...Bo,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new ko({container:i,source:o,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return D(o),new Mr({connection:o,meta:a,container:i,source:t,format:e,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Be.CHROMECAST:Be.SCREEN}chooseFormat(e){switch(e){case Be.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Be.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return N(e)}}skipFormat(e){switch(e){case Be.SCREEN:return this.screenFormatsIterator.next();case Be.CHROMECAST:return this.chromecastFormatsIterator.next();default:return N(e)}}handleNoFormatsError(e){switch(e){case Be.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Be.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return N(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 a=new URL(s);return a.host=t,a.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,a])=>[s,i(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,i=0;const s=ne();return e.add(O(this.providerOutput.error$,Co({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(A(a=>({id:`ProviderHangup:${a}`,category:x.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(K(({to:n})=>n===f.PLAYING),be()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===Be.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Be.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===x.NETWORK,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit,h=c&&(o&&t||!d),u=a.id.includes("partial_metadata"),l=ne()-s;h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u&&l<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():d?(i++,this.reinitProvider()):this.switchToNextProvider(n??Be.SCREEN)}})),e}}const Oo=5e3,Ms="one_video_throughput",Os="one_video_rtt",yi=window.navigator.connection,Ns=()=>{const r=yi?.downlink;if(P(r)&&r!==10)return r*1e3},Fs=()=>{const r=yi?.rtt;if(P(r)&&r!==3e3)return r},Vs=(r,e,t)=>{const i=t*8,s=i/r;return i/(s+e)};class Ti{throughput;rtt;subscription=new se;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Ti.load(Ms)||(e.useBrowserEstimation?Ns():void 0)||Oo,i=Ti.load(Os)??(e.useBrowserEstimation?Fs():void 0)??0;if(this.throughput$=new m(t),this.rtt$=new m(i),this.rttAdjustedThroughput$=new m(Vs(t,i,e.rttPenaltyRequestSize)),this.throughput=cs.getSmoothedValue(t,-1,e),this.rtt=cs.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=Ns();n&&this.throughput.next(n);const o=Fs();P(o)&&this.rtt.next(o)};yi&&"onchange"in yi&&this.subscription.add(M(yi,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{Zi.set(Ms,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{Zi.set(Os,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Le({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(A(({throughput:s,rtt:a})=>Vs(s,a,e.rttPenaltyRequestSize)),K(s=>{const a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ne();const s=new se;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(M(e,"progress").pipe(be()).subscribe(a=>{t=a.loaded,i=ne()}));break;case 1:case 0:s.add(M(e,"loadstart").subscribe(()=>{t=0,i=ne()}));break}s.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),c=n-t,d=o-i;this.addRawSpeed(c,d,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,a=ne(),n=0,o=ne();const c=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},d=async({done:h,value:u})=>{if(h)!t&&this.addRawSpeed(s,ne()-a,1),this.concurrentDownloads.delete(e);else if(u){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=u.byteLength;else{const p=o-a;p&&this.addRawSpeed(n,p,1,t),n=u.byteLength,a=ne()}o=ne()}else s+=u.byteLength,n+=u.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await i?.read().then(d,c)}};this.concurrentDownloads.add(e),i?.read().then(d,c)}addRawSpeed(e,t,i=1,s=!1){if(Ti.sanityCheck(e,t,s)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,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=Zi.get(e);if(P(t))return parseInt(t,10)??void 0}}const Us={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:Je.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:Rt.VP9,androidPreferredFormat:wt.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}},No=r=>({...wr(r,Us),configName:[...r.configName??[],...Us.configName]});var Hs=({seekState:r,position$:e})=>O(r.stateChangeEnded$.pipe(A(({to:t})=>t.state===j.None?void 0:(t.position??NaN)/1e3),K(P)),e.pipe(K(()=>r.getState().state===j.None))),Fo=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return D(e,`Wrong container or containerId {${r.container}}`),e};const Vo=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(K(s=>s.length>0),be()).subscribe(s=>{s.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};class md{subscription=new se;domContainer;providerContainer;chromecastInitializer;logger=new Dr;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new de(f.STOPPED),seekState:new de({state:j.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!0),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),internalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({}),cameraOrientation:new de({x:0,y:0})};info={playbackState$:new m(f.STOPPED),position$:new m(0),duration$:new m(1/0),muted$:new m(!1),volume$:new m(1),availableQualities$:new m([]),availableQualitiesFps$:new m({}),availableAudioTracks$:new m([]),isAudioAvailable$:new m(!0),currentQuality$:new m(void 0),isAutoQualityEnabled$:new m(!0),autoQualityLimitingAvailable$:new m(!1),autoQualityLimits$:new m({}),currentPlaybackRate$:new m(1),currentBuffer$:new m({start:0,end:0}),isBuffering$:new m(!0),isStalled$:new m(!1),isEnded$:new m(!1),isLooped$:new m(!1),isLive$:new m(void 0),canChangePlaybackSpeed$:new m(void 0),atLiveEdge$:new m(void 0),atLiveDurationEdge$:new m(void 0),liveTime$:new m(void 0),liveBufferTime$:new m(void 0),currentFormat$:new m(void 0),availableTextTracks$:new m([]),currentTextTrack$:new m(void 0),throughputEstimation$:new m(void 0),rttEstimation$:new m(void 0),videoBitrate$:new m(void 0),hostname$:new m(void 0),httpConnectionType$:new m(void 0),httpConnectionReused$:new m(void 0),surface$:new m(xt.NONE),chromecastState$:new m(Re.NOT_AVAILABLE),chromecastDeviceName$:new m(void 0),intrinsicVideoSize$:new m(void 0),availableSources$:new m(void 0),is3DVideo$:new m(!1)};events={inited$:new I,ready$:new I,started$:new I,playing$:new I,paused$:new I,stopped$:new I,willStart$:new I,willResume$:new I,willPause$:new I,willStop$:new I,willDestruct$:new I,watchCoverageRecord$:new I,watchCoverageLive$:new I,managedError$:new I,fatalError$:new I,ended$:new I,looped$:new I,seeked$:new I,willSeek$:new I,firstBytes$:new I,firstFrame$:new I,canplay$:new I,log$:new I};experimental={element$:new m(void 0),tuningConfigName$:new m([]),enableDebugTelemetry$:new m(!1),dumpTelemetry:jr};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=No(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ti(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const a=Reflect.get(t,i,s);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const c=n.map(u=>JSON.stringify(u,(l,p)=>{const S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),d=`Player.${String(i)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:x.WTF,message:h,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Fo(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Mo({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()===f.STOPPED&&e.startTransitionTo(f.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==f.PLAYING&&t.startTransitionTo(f.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?M(document,"visibilitychange").pipe(be()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==f.PAUSED&&e.startTransitionTo(f.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==f.STOPPED&&e.startTransitionTo(f.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:j.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()===Re.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()===Re.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){D(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(K(i=>i.length>0),be()).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){D(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 Vo(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(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+a.x,y:s.y+a.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(Y(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===j.None?void 0:t.position;return P(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(O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(A(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(K(({from:e})=>e===f.STOPPED),be()).subscribe(()=>{this.initedAt=ne(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case f.READY:this.events.ready$.next();break;case f.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case f.PAUSED:this.events.paused$.next();break;case f.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case f.PAUSED:this.events.willPause$.next();break;case f.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case f.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===j.Requested?this.desiredState.seekState.setState({...n,state:j.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:x.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===j.Applying&&(this.desiredState.seekState.setState({state:j.None}),this.events.seeked$.next())})).add(e.current$.pipe(A(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(A(n=>n.destination),le()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(A(n=>n.map(({quality:o})=>o).sort((o,c)=>Yt(o)?1:Yt(c)?-1:ei(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const c of n)c.fps&&(o[c.quality]=c.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.hostname$.pipe(le()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(le()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(le()).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(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(A(n=>n?{start:n.from,end:n.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(Le({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Hs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(A(({isLive:n,position:o,isLowLatency:c})=>{const d=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),le(),vi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Le({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(A(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),le(),vi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(A(n=>n.muted),le()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(A(n=>n.volume),le()).subscribe(this.info.volume$)).add(Hs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(ti(!0)),e.providerOutput.seekedEvent$.pipe(ti(!1))).pipe(le()).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(A(n=>({id:n?`No${n}`:"NoProviders",category:x.VIDEO_PIPELINE,message:n?`${n} 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(be(),A(n=>n??ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(be(),A(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(be(),A(()=>ne()-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 m(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new m(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(K(({to:n})=>n===f.PLAYING),be()).subscribe(()=>i.next(!1)));let s=0;const a=O(e.providerOutput.isBuffering$,t,i).pipe(A(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),le());this.subscription.add(a.subscribe(n=>{n?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(O(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(O(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let h;d===Re.CONNECTED?h=xt.SECOND_SCREEN:c?n?h=xt.PIP:o?h=xt.FULLSCREEN:h=xt.INLINE:h=xt.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(A(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new se;this.subscription.add(t),this.subscription.add(e.current$.pipe(le((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),be()).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=qt(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(O(this.desiredState.videoTrack.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(A(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;D(this.providerContainer),D(e),Qr(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Wr(t)),this.providerContainer.current$.subscribe(({type:t})=>Li("provider",t)),e.duration$.subscribe(t=>Li("duration",t)),e.availableVideoTracks$.pipe(K(t=>!!t.length),be()).subscribe(t=>Li("tracks",t)),this.events.fatalError$.subscribe(new ft("fatalError")),this.events.managedError$.subscribe(new ft("managedError")),e.position$.subscribe(new ft("position")),e.currentVideoTrack$.pipe(A(t=>t?.quality)).subscribe(new ft("quality")),this.info.currentBuffer$.subscribe(new ft("buffer")),e.isBuffering$.subscribe(new ft("isBuffering"))].forEach(t=>this.subscription.add(t)),Li("codecs",Lo())}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:x.DOM,message:String(s)})})};this.subscription.add(O(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===f.PLAYING,n=!!e&&!e?.released;s&&a?n||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 gd=`@vkontakte/videoplayer-core@${Pr}`;export{Re as ChromecastState,Ei as HttpConnectionType,yd as Observable,f as PlaybackState,md as Player,gd as SDK_VERSION,Td as Subject,vd as Subscription,xt as Surface,Pr as VERSION,Ed as ValueSubject,y as VideoFormat,kd as VideoQuality};