@vkontakte/videoplayer-core 2.0.95 → 2.0.96

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.95
3
- * Tue, 12 Dec 2023 10:39:51 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-95/doc/
2
+ * @vkontakte/videoplayer-core v2.0.96
3
+ * Wed, 13 Dec 2023 12:11:59 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-96/doc/
5
5
  */
6
- import{ValueSubject as m,Subject as x,Subscription as te,isNonNullable as w,ErrorCategory as L,isNullable as J,fromEvent as C,assertNever as M,merge as B,tap as ei,map as y,observableFrom as $e,filterChanged as ce,assertNonNullable as P,debounce as Ie,getHighestQuality as xs,timeout as Rs,getCurrentBrowser as wi,CurrentClientBrowser as rs,combine as _e,once as le,mapTo as yt,filter as K,now as ue,videoSizeToQuality as pt,isInvariantQuality as Ot,isHigher as Bt,isLower as Kt,isHigherOrEqual as yi,isLowerOrEqual as ns,Observable as di,interval as ti,VideoQuality as Re,videoQualityToHeight as Ls,abortable as De,getExponentialDelay as Li,throttle as Cs,CurrentClientDevice as Is,safeStorage as Si,fillWithDefault as Bs,Logger as Ms}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as hn,Subject as ln,Subscription as pn,ValueSubject as fn,VideoQuality as mn}from"@vkontakte/videoplayer-shared/esnext.esm.js";import Ns from"lodash/debounce.js";const Os="2.0.95";var l;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(l||(l={}));var S;(function(a){a.MPEG="MPEG",a.DASH="DASH",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(S||(S={}));var Te;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(Te||(Te={}));var ge;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(ge||(ge={}));var Ft;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Ft||(Ft={}));var H;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(H||(H={}));var st;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(st||(st={}));var Fs=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Vs{connection$=new m(void 0);castState$=new m(ge.NOT_AVAILABLE);errorEvent$=new x;contentId;realCastState$=new m(ge.NOT_AVAILABLE);subscription=new te;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=w(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},s||Fs("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(){w(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();J(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();J(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(C(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 M(s.sessionState)}})).add(B(C(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ei(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),y(s=>s.castState)),$e([i.getCastState()])).pipe(ce(),y(Us),ei(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const r=s===ge.CONNECTED,n=w(this.connection$.getValue());if(r&&!n){const o=i.getCurrentSession();P(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(J(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!r&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===ge.CONNECTED?w(this.connection$.getValue())?ge.CONNECTED:ge.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 Us=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return M(a)}};var fe;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Ne=(a,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{if(e===0)return a;const i=new URL(a);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:M(t)}return a};const Ci=(a,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:M(e)}};var D=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class ne{state;prevState;transition;transitionStarted$=new x;transitionEnded$=new x;transitionUpdated$=new x;forceChanged$=new x;stateChangeStarted$=B(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=B(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||w(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 Hs=a=>{switch(a){case S.MPEG:case S.DASH:case S.DASH_SEP:case S.DASH_ONDEMAND:case S.DASH_WEBM:case S.DASH_WEBM_AV1:case S.HLS:case S.HLS_ONDEMAND:return!1;case S.DASH_LIVE:case S.DASH_LIVE_CMAF:case S.HLS_LIVE:case S.HLS_LIVE_CMAF:case S.DASH_LIVE_WEBM:case S.WEB_RTC_LIVE:return!0;default:return M(a)}};var V;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const Ys=5,Gs=5,qs=500,Ii=7e3;class zs{subscription=new te;loadMediaTimeoutSubscription=new te;videoState=new ne(V.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(Hs(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 te;this.subscription.add(e),this.subscription.add(B(this.videoState.stateChangeStarted$.pipe(y(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(y(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,r)=>this.subscription.add(s.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new x;e.add(s.pipe(Ie(qs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(C(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===H.Applying||Math.abs(o-r)>Ys)&&s.next(o),r=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:r}=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()&&r.duration-r.currentTime<Gs&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(this.params.desiredState.playbackState,l.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:M(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=B(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(Ie(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(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.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:H.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===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&D(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.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,r;switch(e){case S.MPEG:{const d=t[e];P(d);const h=xs(Object.keys(d));P(h);const u=d[h];P(u),i=u,s="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case S.HLS:case S.HLS_ONDEMAND:{const d=t[e];P(d),i=d.url,s="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case S.DASH_SEP:case S.DASH_ONDEMAND:case S.DASH_WEBM:case S.DASH_WEBM_AV1:{const d=t[e];P(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case S.DASH_LIVE_CMAF:{const d=t[e];P(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case S.HLS_LIVE:case S.HLS_LIVE_CMAF:{const d=t[e];P(d),i=Ne(d.url),s="application/x-mpegurl",r=chrome.cast.media.StreamType.LIVE;break}case S.DASH:case S.DASH_LIVE:case S.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 S.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=r,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return w(o)&&(n.metadata.title=o),w(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===H.Applying||i.state===H.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,r)=>{this.loadMediaTimeoutSubscription.add(Rs(Ii).subscribe(()=>r(`timeout(${Ii})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.VIDEO_PIPELINE,message:r,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(),r=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(r)};`}),i===l.STOPPED){e!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!t){if(s?.to!==l.PAUSED&&r.state===H.Requested&&e!==V.STOPPED){this.seek(r.position/1e3);return}switch(i){case l.READY:{switch(e){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}case l.PLAYING:{switch(e){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}case l.PAUSED:{switch(e){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}default:M(i)}}}}var Ws=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,r=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>r(n),t&&i&&e?.()}}},!0)},Qs=a=>{const e=new m(1/0),t=new x,i=new m(void 0),s=new m(void 0);let r=NaN,n=!1;const o=()=>{r=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(b=>b.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const b=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),v=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??b*1e3??NaN;w(v)&&!isNaN(v)&&e.next(v)}const p=u["x-delivery-type"]??Ft.HTTP1,f={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(p),s.next(f)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-r))};return a.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(p){if(p.request.type==="MPD"){const f=p.onload,b=p.progress;p.onload=function(...E){return c(this),f(...E)},p.progress=function(...E){return d(this),b(...E)},o()}return u(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},vt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},js=a=>a.extend("RequestModifier",()=>({modifyRequestURL:vt}),!0),Js=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,r]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${r}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Oe=(a,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:r}={})=>{const n=a.getState(),o=e(),c=J(s),d=new te;return s&&d.add(s.subscribe(h=>{const u=a.getState();i(h,u)&&a.setState(h)},r)),i(o,n)||(t(n),c&&a.setState(n)),d.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),c&&a.setState(h.to)},r)),d},ft=(a,e,t)=>Oe(e,()=>a.loop,i=>{w(i)&&(a.loop=i)},{onError:t}),Xe=(a,e,t,i)=>Oe(e,()=>({muted:a.muted,volume:a.volume}),s=>{w(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,r)=>s===r||s?.muted===r?.muted&&s?.volume===r?.volume,changed$:t,onError:i}),nt=(a,e,t,i)=>Oe(e,()=>a.playbackRate,s=>{w(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),Xs=a=>["__",a.language,a.label].join("|"),Ks=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class Ge{available$=new x;current$=new m(void 0);error$=new x;video;cueSettings;subscription=new te;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=r=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};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(Oe(t.internalTextTracks,()=>Object.values(this.internalTracks),r=>{w(r)&&this.setInternal(r)},{equal:(r,n)=>w(r)&&w(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(y(r=>r.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(Oe(t.externalTextTracks,()=>Object.values(this.externalTracks),r=>{w(r)&&this.setExternal(r)},{equal:(r,n)=>w(r)&&w(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(y(r=>r.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(Oe(t.currentTextTrack,()=>{if(this.video)return;const r=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return r&&this.htmlTextTrackToITextTrack(r).id},r=>this.select(r),{changed$:this.current$,onError:s})),this.subscription.add(Oe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(C(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(B(C(e,"addtrack"),C(e,"removetrack"),$e(["init"])).pipe(y(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ce((i,s)=>i.length===s.length&&i.every(({id:r},n)=>r===s[n].id))).subscribe(this.available$)),this.subscription.add(B(C(e,"change"),$e(["init"])).pipe(y(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),y(i=>i&&this.htmlTextTrackToITextTrack(i).id),ce()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(C(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(C(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;w(t.align)&&(s.align=t.align),w(t.position)&&(s.position=t.position),w(t.size)&&(s.size=t.size),w(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ge.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Xs(e),r=this.externalTracks.has(s),n=s.includes("auto");return r?{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:r})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===r)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(J(e)||!Ks(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){P(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){P(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 Pi=a=>{a.removeAttribute("src"),a.load()},Zs=a=>{try{a.pause(),a.playbackRate=0,Pi(a),a.remove()}catch(e){console.error(e)}};class ea{attribute="data-pool-reused";get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const vi=window.WeakMap?new WeakMap:new ea,Ke=a=>{let e=a.querySelector("video");const t=!!e;return e?Pi(e):(e=document.createElement("video"),a.appendChild(e)),vi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ze=a=>{const e=vi.get(a);vi.delete(a),e?Pi(a):Zs(a)};class ci{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 os=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Bi=a=>{const e=os(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ta=a=>{const e=os(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ei=3;class ia{_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 r=this._source.buffered.end(t);s>e&&s-e<Ei&&(s=e),this._buffer.push({from:s,to:r,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ei))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:r})=>{const n=s>=e&&s<t,o=r>=e&&r<t;n&&o||(n?i(t,r):o?i(s,e):s<e&&r>t?(i(t,r),i(s,e)):i(s,r))})}destroy(){this._buffer=[]}}var ds=(a,e,t=Ei)=>{let i=0,s=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=r-1;c>=0;c--)a.end(c)+t>=i&&(i=a.start(c));for(let c=r+1;c<a.length;c++)a.start(c)-t<=s&&(s=a.end(c))}}return{from:i,to:s}};const et=a=>{const e=g=>C(a,g).pipe(yt(void 0)),i=B(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>C(a,g))).pipe(y(g=>g.type==="ended"?a.readyState<2:a.readyState<3),ce()),s=B(C(a,"progress"),C(a,"timeupdate")).pipe(y(()=>ds(a.buffered,a.currentTime))),n=wi().browser===rs.Safari?_e({play:e("play").pipe(le()),playing:e("playing")}).pipe(yt(void 0)):e("playing"),o=C(a,"volumechange").pipe(y(()=>({muted:a.muted,volume:a.volume}))),c=C(a,"ratechange").pipe(y(()=>a.playbackRate)),d=C(a,"error").pipe(K(()=>!!(a.error||a.played.length)),y(()=>{const g=a.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=C(a,"timeupdate").pipe(y(()=>a.currentTime)),u=new x,p=.3;let f;h.subscribe(g=>{a.loop&&w(f)&&w(g)&&f>=a.duration-p&&g<=p&&u.next(f),f=g});const b=C(a,"enterpictureinpicture"),E=C(a,"leavepictureinpicture"),v=new m(ta(a));b.subscribe(()=>v.next(!0)),E.subscribe(()=>v.next(!1));const R=new m(Bi(a));return C(a,"fullscreenchange").pipe(y(()=>Bi(a))).subscribe(R),{playing$:n,pause$:e("pause").pipe(K(()=>!a.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$:C(a,"durationchange").pipe(y(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:v,inFullscreen$:R}},Di=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let _i=!1,je={};const sa=a=>{_i=a},aa=()=>{je={}},ra=a=>{a(je)},Qt=(a,e)=>{_i&&(je.meta=je.meta??{},je.meta[a]=e)};class Ue{name;constructor(e){this.name=e}next(e){if(!_i)return;je.series=je.series??{};const t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}}var ht;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(ht||(ht={}));const na=new Ue("best_bitrate"),oa=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class da{last;history={};recordSelection(e){this.history[e.id]=ue()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const kt=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},b=f&&pt(f),E=i.considerPlaybackRate&&w(o)?o:1,v=a.filter(A=>!Ot(A.quality)).sort((A,F)=>Bt(A.quality,F.quality)?-1:1),R=v.at(-1)?.quality,N=v.at(0)?.quality,g=J(s)||w(s.min)&&w(s.max)&&Kt(s.max,s.min)||w(s.min)&&N&&Bt(s.min,N)||w(s.max)&&R&&Kt(s.max,R),$=E*oa(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},W=v.filter(A=>(b?Kt(A.quality,b):!0)?(w(t)&&isFinite(t)&&w(A.bitrate)?t-r>=A.bitrate*$:!0)?i.lazyQualitySwitch&&w(i.minBufferToSwitchUp)&&c&&!Ot(c.quality)&&(n??0)<i.minBufferToSwitchUp&&Bt(A.quality,c.quality)?(k[A.quality]=ht.Buffer,!1):!!h&&yi(A.quality,h)?(k[A.quality]=ht.DroppedFramesLimit,!1):g||(J(s.max)||ns(A.quality,s.max))&&(J(s.min)||yi(A.quality,s.min))?!0:(k[A.quality]=ht.FitsQualityLimits,!1):(k[A.quality]=ht.FitsThroughput,!1):(k[A.quality]=ht.FitsContainer,!1))[0];W&&W.bitrate&&na.next(W.bitrate);const G=W??v[Math.ceil((v.length-1)/2)]??a[0];G.quality!==d?.last?.quality&&u({message:`
6
+ import{ValueSubject as m,Subject as x,Subscription as te,isNonNullable as w,ErrorCategory as L,isNullable as J,fromEvent as C,assertNever as M,merge as B,tap as ei,map as y,observableFrom as $e,filterChanged as ce,assertNonNullable as P,debounce as Ie,getHighestQuality as xs,timeout as Rs,getCurrentBrowser as wi,CurrentClientBrowser as rs,combine as _e,once as le,mapTo as yt,filter as K,now as ue,videoSizeToQuality as pt,isInvariantQuality as Ot,isHigher as Bt,isLower as Kt,isHigherOrEqual as yi,isLowerOrEqual as ns,Observable as di,interval as ti,VideoQuality as Re,videoQualityToHeight as Ls,abortable as De,getExponentialDelay as Li,throttle as Cs,CurrentClientDevice as Is,safeStorage as Si,fillWithDefault as Bs,Logger as Ms}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as hn,Subject as ln,Subscription as pn,ValueSubject as fn,VideoQuality as mn}from"@vkontakte/videoplayer-shared/esnext.esm.js";import Ns from"lodash/debounce.js";const Os="2.0.96";var l;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(l||(l={}));var S;(function(a){a.MPEG="MPEG",a.DASH="DASH",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(S||(S={}));var Te;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(Te||(Te={}));var ge;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(ge||(ge={}));var Ft;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Ft||(Ft={}));var H;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(H||(H={}));var st;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(st||(st={}));var Fs=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Vs{connection$=new m(void 0);castState$=new m(ge.NOT_AVAILABLE);errorEvent$=new x;contentId;realCastState$=new m(ge.NOT_AVAILABLE);subscription=new te;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=w(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},s||Fs("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(){w(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();J(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();J(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(C(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 M(s.sessionState)}})).add(B(C(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ei(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),y(s=>s.castState)),$e([i.getCastState()])).pipe(ce(),y(Us),ei(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const r=s===ge.CONNECTED,n=w(this.connection$.getValue());if(r&&!n){const o=i.getCurrentSession();P(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(J(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!r&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===ge.CONNECTED?w(this.connection$.getValue())?ge.CONNECTED:ge.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 Us=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return M(a)}};var fe;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Ne=(a,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{if(e===0)return a;const i=new URL(a);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:M(t)}return a};const Ci=(a,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:M(e)}};var D=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class ne{state;prevState;transition;transitionStarted$=new x;transitionEnded$=new x;transitionUpdated$=new x;forceChanged$=new x;stateChangeStarted$=B(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=B(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||w(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 Hs=a=>{switch(a){case S.MPEG:case S.DASH:case S.DASH_SEP:case S.DASH_ONDEMAND:case S.DASH_WEBM:case S.DASH_WEBM_AV1:case S.HLS:case S.HLS_ONDEMAND:return!1;case S.DASH_LIVE:case S.DASH_LIVE_CMAF:case S.HLS_LIVE:case S.HLS_LIVE_CMAF:case S.DASH_LIVE_WEBM:case S.WEB_RTC_LIVE:return!0;default:return M(a)}};var V;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const Ys=5,Gs=5,qs=500,Ii=7e3;class zs{subscription=new te;loadMediaTimeoutSubscription=new te;videoState=new ne(V.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(Hs(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 te;this.subscription.add(e),this.subscription.add(B(this.videoState.stateChangeStarted$.pipe(y(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(y(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,r)=>this.subscription.add(s.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new x;e.add(s.pipe(Ie(qs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(C(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===H.Applying||Math.abs(o-r)>Ys)&&s.next(o),r=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:r}=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()&&r.duration-r.currentTime<Gs&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(this.params.desiredState.playbackState,l.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:M(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=B(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(Ie(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(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.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:H.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===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&D(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.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,r;switch(e){case S.MPEG:{const d=t[e];P(d);const h=xs(Object.keys(d));P(h);const u=d[h];P(u),i=u,s="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case S.HLS:case S.HLS_ONDEMAND:{const d=t[e];P(d),i=d.url,s="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case S.DASH_SEP:case S.DASH_ONDEMAND:case S.DASH_WEBM:case S.DASH_WEBM_AV1:{const d=t[e];P(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case S.DASH_LIVE_CMAF:{const d=t[e];P(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case S.HLS_LIVE:case S.HLS_LIVE_CMAF:{const d=t[e];P(d),i=Ne(d.url),s="application/x-mpegurl",r=chrome.cast.media.StreamType.LIVE;break}case S.DASH:case S.DASH_LIVE:case S.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 S.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=r,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return w(o)&&(n.metadata.title=o),w(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===H.Applying||i.state===H.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,r)=>{this.loadMediaTimeoutSubscription.add(Rs(Ii).subscribe(()=>r(`timeout(${Ii})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.VIDEO_PIPELINE,message:r,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(),r=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(r)};`}),i===l.STOPPED){e!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!t){if(s?.to!==l.PAUSED&&r.state===H.Requested&&e!==V.STOPPED){this.seek(r.position/1e3);return}switch(i){case l.READY:{switch(e){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}case l.PLAYING:{switch(e){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}case l.PAUSED:{switch(e){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}default:M(i)}}}}var Ws=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,r=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>r(n),t&&i&&e?.()}}},!0)},Qs=a=>{const e=new m(1/0),t=new x,i=new m(void 0),s=new m(void 0);let r=NaN,n=!1;const o=()=>{r=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(b=>b.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const b=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),v=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??b*1e3??NaN;w(v)&&!isNaN(v)&&e.next(v)}const p=u["x-delivery-type"]??Ft.HTTP1,f={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(p),s.next(f)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-r))};return a.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(p){if(p.request.type==="MPD"){const f=p.onload,b=p.progress;p.onload=function(...E){return c(this),f(...E)},p.progress=function(...E){return d(this),b(...E)},o()}return u(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},vt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},js=a=>a.extend("RequestModifier",()=>({modifyRequestURL:vt}),!0),Js=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,r]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${r}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Oe=(a,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:r}={})=>{const n=a.getState(),o=e(),c=J(s),d=new te;return s&&d.add(s.subscribe(h=>{const u=a.getState();i(h,u)&&a.setState(h)},r)),i(o,n)||(t(n),c&&a.setState(n)),d.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),c&&a.setState(h.to)},r)),d},ft=(a,e,t)=>Oe(e,()=>a.loop,i=>{w(i)&&(a.loop=i)},{onError:t}),Xe=(a,e,t,i)=>Oe(e,()=>({muted:a.muted,volume:a.volume}),s=>{w(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,r)=>s===r||s?.muted===r?.muted&&s?.volume===r?.volume,changed$:t,onError:i}),nt=(a,e,t,i)=>Oe(e,()=>a.playbackRate,s=>{w(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),Xs=a=>["__",a.language,a.label].join("|"),Ks=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class Ge{available$=new x;current$=new m(void 0);error$=new x;video;cueSettings;subscription=new te;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=r=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};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(Oe(t.internalTextTracks,()=>Object.values(this.internalTracks),r=>{w(r)&&this.setInternal(r)},{equal:(r,n)=>w(r)&&w(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(y(r=>r.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(Oe(t.externalTextTracks,()=>Object.values(this.externalTracks),r=>{w(r)&&this.setExternal(r)},{equal:(r,n)=>w(r)&&w(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(y(r=>r.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(Oe(t.currentTextTrack,()=>{if(this.video)return;const r=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return r&&this.htmlTextTrackToITextTrack(r).id},r=>this.select(r),{changed$:this.current$,onError:s})),this.subscription.add(Oe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(C(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(B(C(e,"addtrack"),C(e,"removetrack"),$e(["init"])).pipe(y(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ce((i,s)=>i.length===s.length&&i.every(({id:r},n)=>r===s[n].id))).subscribe(this.available$)),this.subscription.add(B(C(e,"change"),$e(["init"])).pipe(y(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),y(i=>i&&this.htmlTextTrackToITextTrack(i).id),ce()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(C(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(C(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;w(t.align)&&(s.align=t.align),w(t.position)&&(s.position=t.position),w(t.size)&&(s.size=t.size),w(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ge.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Xs(e),r=this.externalTracks.has(s),n=s.includes("auto");return r?{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:r})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===r)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(J(e)||!Ks(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){P(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){P(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 Pi=a=>{a.removeAttribute("src"),a.load()},Zs=a=>{try{a.pause(),a.playbackRate=0,Pi(a),a.remove()}catch(e){console.error(e)}};class ea{attribute="data-pool-reused";get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const vi=window.WeakMap?new WeakMap:new ea,Ke=a=>{let e=a.querySelector("video");const t=!!e;return e?Pi(e):(e=document.createElement("video"),a.appendChild(e)),vi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ze=a=>{const e=vi.get(a);vi.delete(a),e?Pi(a):Zs(a)};class ci{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 os=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Bi=a=>{const e=os(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ta=a=>{const e=os(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ei=3;class ia{_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 r=this._source.buffered.end(t);s>e&&s-e<Ei&&(s=e),this._buffer.push({from:s,to:r,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ei))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:r})=>{const n=s>=e&&s<t,o=r>=e&&r<t;n&&o||(n?i(t,r):o?i(s,e):s<e&&r>t?(i(t,r),i(s,e)):i(s,r))})}destroy(){this._buffer=[]}}var ds=(a,e,t=Ei)=>{let i=0,s=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=r-1;c>=0;c--)a.end(c)+t>=i&&(i=a.start(c));for(let c=r+1;c<a.length;c++)a.start(c)-t<=s&&(s=a.end(c))}}return{from:i,to:s}};const et=a=>{const e=g=>C(a,g).pipe(yt(void 0)),i=B(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>C(a,g))).pipe(y(g=>g.type==="ended"?a.readyState<2:a.readyState<3),ce()),s=B(C(a,"progress"),C(a,"timeupdate")).pipe(y(()=>ds(a.buffered,a.currentTime))),n=wi().browser===rs.Safari?_e({play:e("play").pipe(le()),playing:e("playing")}).pipe(yt(void 0)):e("playing"),o=C(a,"volumechange").pipe(y(()=>({muted:a.muted,volume:a.volume}))),c=C(a,"ratechange").pipe(y(()=>a.playbackRate)),d=C(a,"error").pipe(K(()=>!!(a.error||a.played.length)),y(()=>{const g=a.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=C(a,"timeupdate").pipe(y(()=>a.currentTime)),u=new x,p=.3;let f;h.subscribe(g=>{a.loop&&w(f)&&w(g)&&f>=a.duration-p&&g<=p&&u.next(f),f=g});const b=C(a,"enterpictureinpicture"),E=C(a,"leavepictureinpicture"),v=new m(ta(a));b.subscribe(()=>v.next(!0)),E.subscribe(()=>v.next(!1));const R=new m(Bi(a));return C(a,"fullscreenchange").pipe(y(()=>Bi(a))).subscribe(R),{playing$:n,pause$:e("pause").pipe(K(()=>!a.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$:C(a,"durationchange").pipe(y(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:v,inFullscreen$:R}},Di=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let _i=!1,je={};const sa=a=>{_i=a},aa=()=>{je={}},ra=a=>{a(je)},Qt=(a,e)=>{_i&&(je.meta=je.meta??{},je.meta[a]=e)};class Ue{name;constructor(e){this.name=e}next(e){if(!_i)return;je.series=je.series??{};const t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}}var ht;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(ht||(ht={}));const na=new Ue("best_bitrate"),oa=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class da{last;history={};recordSelection(e){this.history[e.id]=ue()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const kt=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},b=f&&pt(f),E=i.considerPlaybackRate&&w(o)?o:1,v=a.filter(A=>!Ot(A.quality)).sort((A,F)=>Bt(A.quality,F.quality)?-1:1),R=v.at(-1)?.quality,N=v.at(0)?.quality,g=J(s)||w(s.min)&&w(s.max)&&Kt(s.max,s.min)||w(s.min)&&N&&Bt(s.min,N)||w(s.max)&&R&&Kt(s.max,R),$=E*oa(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},W=v.filter(A=>(b?Kt(A.quality,b):!0)?(w(t)&&isFinite(t)&&w(A.bitrate)?t-r>=A.bitrate*$:!0)?i.lazyQualitySwitch&&w(i.minBufferToSwitchUp)&&c&&!Ot(c.quality)&&(n??0)<i.minBufferToSwitchUp&&Bt(A.quality,c.quality)?(k[A.quality]=ht.Buffer,!1):!!h&&yi(A.quality,h)?(k[A.quality]=ht.DroppedFramesLimit,!1):g||(J(s.max)||ns(A.quality,s.max))&&(J(s.min)||yi(A.quality,s.min))?!0:(k[A.quality]=ht.FitsQualityLimits,!1):(k[A.quality]=ht.FitsThroughput,!1):(k[A.quality]=ht.FitsContainer,!1))[0];W&&W.bitrate&&na.next(W.bitrate);const G=W??v[Math.ceil((v.length-1)/2)]??a[0];G.quality!==d?.last?.quality&&u({message:`
7
7
  [available tracks] ${a.map(A=>A.quality).join(", ")}
8
8
 
9
9
  [limit params]
@@ -26,7 +26,7 @@ import{ValueSubject as m,Subject as x,Subscription as te,isNonNullable as w,Erro
26
26
  [selected track] ${G.quality}
27
27
  `});const Q=G&&d&&d.history[G.id]&&ue()-d.history[G.id]<=i.trackCooldown&&(!d.last||G.id!==d.last.id);if(G?.id&&d&&!Q&&d.recordSelection(G),Q&&d?.last){const A=d.last;return d?.recordSwitch(A),u({message:`
28
28
  [last selected] ${A.quality}
29
- `}),A}return d?.recordSwitch(G),G};var ke=a=>new URL(a).hostname;const ca=300,ii=(a,e=ca)=>new di(t=>{const{width:i,height:s}=a.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const r=new ResizeObserver(Ns(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),w(c)&&w(d)&&t.next({width:c,height:d})},e));return r.observe(a),()=>r.disconnect()});class ui{onDroopedVideoFramesLimit$=new x;subscription=new te;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new x;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(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=ti(this.droppedFramesChecker.checkTime).pipe(K(()=>this.playing),K(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Ie(this.droppedFramesChecker.checkTime)),i=B(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&&!Ot(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,r=1-(i-s)/i;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&Bt(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])=>Kt(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 xt={};var Y;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));const pe=(a,e)=>new di(t=>{const i=s=>t.next(s);return a.on(e,i),()=>a.off(e,i)});class Mi{subscription=new te;videoState=new ne(Y.DOWNLOADING_LIB);video;player;params;textTracksManager=new Ge;droppedFramesManager=new ui;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 ci;constructor(e){this.video=Ke(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(ke(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||(xt.MediaPlayer=s.MediaPlayer,xt.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(xt.MediaPlayer,"dashjs not loaded"),P(xt.Debug,"dashjs not loaded"),this.player=xt.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?Di(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Js(this.player),Ws(this.player),this.params.tuning.requestQuick&&js(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:g})},s=(g,$)=>this.subscription.add(g.subscribe($,i));s(ii(this.video),this.elementSize$),s(pe(this.player,"error").pipe(y(g=>{const $=typeof g.error=="object"?g.error.code:g.error,k=typeof g.error=="object"?g.error.message:void 0;return{id:`DashJS#${$}`,message:k}})),e.error$),s(pe(this.player,"playbackError").pipe(y(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const r=pe(this.player,"qualityChangeRendered").pipe(K(({mediaType:g})=>g==="video"),y(({newQuality:g})=>this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g)?.track));r.pipe(K(w)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(K(({to:g})=>g===Y.STREAM_INITIALIZED),le()).subscribe(()=>{this.subscription.add(Oe(t.videoTrack,()=>{const g=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g)?.track?.id},g=>{if(J(g))return;const $=this.videoTracks$.getValue().find(({track:k})=>k.id===g)?.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:r.pipe(y(g=>g?.id)),onError:i}))},i)),this.subscription.add(Oe(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,g=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:g}}}}),{onError:i})),s(pe(this.player,"bufferStateChanged").pipe(K(({mediaType:g})=>g==="video"),y(({state:g})=>g==="bufferStalled")),e.isBuffering$),s(pe(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:$}})=>{const k=this.player.getDashMetrics(),O=k.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),W=k.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type")??Ft.HTTP1,G={1:!0,0:!1}[O]??void 0;this.params.output.httpConnectionType$.next(W),this.params.output.httpConnectionReused$.next(G),e.hostname$.next(ke($))}),s(pe(this.player,"streamInitialized"),({streamInfo:{duration:g,manifestInfo:{isDynamic:$,availableFrom:k}}})=>{this.isLive$.next($),this.availableFrom$.next(k.getTime()),$||e.duration$.next(g);const O=[],W=this.player.getQualityFor("video");let G;for(const Q of this.player.getBitrateInfoListFor("video")){const A=Q.qualityIndex.toString(10),F=pt(Q),q=Q.bitrate/1e3,ie={width:Q.width,height:Q.height},be=this.frameRatesByFrameHeight[Q.height];if(F){const ve={id:A,quality:F,bitrate:q,size:ie,fps:be};O.push({track:ve,bitrateInfo:Q}),Q.qualityIndex===W&&(G=ve)}}this.videoTracks$.next(O),e.availableVideoTracks$.next(O.map(({track:Q})=>Q)),G&&e.currentVideoTrack$.next(G),this.videoState.setState(Y.STREAM_INITIALIZED),this.videoState.startTransitionTo(Y.READY)}),s(pe(this.player,"fragmentLoadingCompleted"),({request:g})=>{if(!g.requestEndDate||!g.firstByteDate||!g.bytesLoaded)return;const $=g.requestEndDate.getTime()-g.firstByteDate.getTime(),k=g.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(k,$)}),s(B(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(),$=kt(this.videoTracks$.getValue().map(({track:W})=>W),{container:this.elementSize$.getValue(),throughput:g,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),k=t.autoVideoTrackLimits.getTransition();k&&e.autoVideoTrackLimits$.next(k.to);const O=this.videoTracks$.getValue().find(({track:W})=>W===$);O?.bitrateInfo&&this.player.setQualityFor("video",O?.bitrateInfo.qualityIndex,!1)}),s(_e({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(K(w))}).pipe(K(({isLive:g})=>g),y(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const n=pe(this.player,"playbackTimeUpdated").pipe(y(({time:g})=>g??0));s(_e({availableFrom:this.availableFrom$.pipe(K(w)),currentTime:n}),({availableFrom:g,currentTime:$})=>this.params.output.liveTime$.next(g+$*1e3)),s(n.pipe(K(()=>this.isLive$.getValue()===!1)),e.position$),s(pe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(pe(this.player,"playbackEnded"),e.endedEvent$),s(pe(this.player,"playbackProgress").pipe(y(()=>ds(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(pe(this.player,"playbackPlaying"),()=>{this.videoState.setState(Y.PLAYING),D(t.playbackState,l.PLAYING)}),s(pe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Y.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(pe(this.player,"playbackPaused"),()=>{this.videoState.setState(Y.PAUSED),D(t.playbackState,l.PAUSED)}),s(pe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY)}),s(this.isLive$,e.isLive$),s(ii(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(Ie(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=Qs(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(le()),e.firstBytesEvent$),s(pe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(_e({isLive:this.isLive$,isShort:e.duration$.pipe(y(g=>g<60))}),({isLive:g,isShort:$})=>{const k=!g&&$;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:k}}})}),s(n.pipe(K(g=>g>this.params.tuning.insufficientBufferRuleMargin),le()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(pe(this.player,"manifestLoaded").pipe(le()).subscribe(()=>{this.subscription.add(pe(this.player,"playbackPlaying").pipe(le(),yt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(pe(this.player,"manifestLoaded"),g=>{if(g.data?.Period?.AdaptationSet){const $=[];for(const k of g.data?.Period?.AdaptationSet)if(k.contentType==="text"){const O=k.Representation?.id,W=new URL(k.Representation?.BaseURL,g.data?.baseUri).toString(),G="internal",Q=k.lang;$.push({id:O,url:W,type:G,language:Q})}t.internalTextTracks.startTransitionTo($)}}),this.subscription.add(ft(this.video,t.isLooped,i));const{volumeState$:p,looped$:f,playbackRateState$:b,inPiP$:E,inFullscreen$:v,pause$:R,playing$:N}=et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:N,pause$:R,tracks$:this.videoTracks$.pipe(y(g=>g.map(({track:$})=>$)))}),this.subscription.add(Xe(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(nt(this.video,t.playbackRate,b,i)),this.subscription.add(E.subscribe(e.inPiP$)),this.subscription.add(v.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(Y.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Y.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=Ne(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(Y.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Y.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(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===Y.DOWNLOADING_LIB||e===Y.STREAM_INITIALIZED))switch(i?.to!==l.PAUSED&&s.state===H.Requested&&e!==Y.STOPPED&&t!==l.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case l.STOPPED:{switch(e){case Y.STOPPED:break;case Y.PLAYING:case Y.PAUSED:case Y.READY:this.stop();break;default:M(e)}break}case l.READY:{switch(e){case Y.STOPPED:this.prepare();break;case Y.PLAYING:case Y.PAUSED:case Y.READY:break;default:M(e)}break}case l.PLAYING:{switch(e){case Y.PLAYING:break;case Y.PAUSED:r&&(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 Y.READY:this.play();break;case Y.STOPPED:this.prepare();break;default:M(e)}break}case l.PAUSED:{switch(e){case Y.PLAYING:this.pause(),this.liveOffset.pause();break;case Y.PAUSED:break;case Y.READY:this.videoState.setState(Y.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED);break;case Y.STOPPED:this.prepare();break;default:M(e)}break}default:M(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}Ze(this.video),this.params.output.element$.next(void 0)}}var Ht=a=>{switch(a){case"mobile":return Re.Q_144P;case"lowest":return Re.Q_240P;case"low":return Re.Q_360P;case"sd":case"medium":return Re.Q_480P;case"hd":case"high":return Re.Q_720P;case"fullhd":case"full":return Re.Q_1080P;case"quadhd":case"quad":return Re.Q_1440P;case"ultrahd":case"ultra":return Re.Q_2160P}};const Ni=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var ot=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!Ni(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return Ni(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function ye(){return ue()}function cs(a){return ye()-a}function Oi(a){const e=a.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 ua(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Zt(a,e,t,i){const s=window.XMLHttpRequest;let r,n,o,c=!1,d=0,h,u,p=!1,f="arraybuffer",b=7e3,E=2e3,v=()=>{if(c)return;P(h);const q=cs(h);let ie;if(q<E){ie=E-q,setTimeout(v,ie);return}E*=2,E>b&&(E=b),n&&n.abort(),n=new s,O()};const R=q=>(r=q,F),N=q=>(u=q,F),g=()=>(f="json",F),$=()=>{if(!c){if(--d>=0){v(),i&&i();return}c=!0,u&&u(),t&&t()}},k=q=>(p=q,F),O=()=>{h=ye(),n=new s,n.open("get",a);let q=0,ie,be=0;const ve=()=>(P(h),Math.max(h,Math.max(ie||0,be||0)));if(r&&n.addEventListener("progress",I=>{const ee=ye();r.updateChunk&&I.loaded>q&&(r.updateChunk(ve(),I.loaded-q),q=I.loaded,ie=ee)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(c)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&r){const ee=n.response.byteLength-q;ee&&r.updateChunk&&r.updateChunk(ve(),ee)}u&&u(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),p){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(be=ye(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),F},F={withBitrateReporting:R,withParallel:k,withJSONResponse:g,withRetryCount:q=>(d=q,F),withRetryInterval:(q,ie)=>(w(q)&&(E=q),w(ie)&&(b=ie),F),withTimeout:q=>(o=q,F),withFinally:N,send:O,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return F}const ha=100,la=2e3,pa=500;let fa=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-pa;if(t-e>la){let i=0,s=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)i+=r.end-r.start,s+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;i+=n;const c=r.bytes*n/o;s+=c,r.start=t,r.bytes-=c}}}if(s>0&&i>0){const r=s*8/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/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>ha&&(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 ma{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}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=ye(),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)},r=c=>{e._complete=1,e._responseData=c,e._downloadTime=ye()-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=Zt(t,r,()=>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=ye()}_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=ye();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 r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=r._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)),r._finallyCB&&r._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(r,e)}},r._cb=t,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=n=>(r._finallyCB=n,r),r}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 jt=1e4,Jt=3,ga=300,Sa=2e3,ba=6e4,Ta=10,ya=1,va=500;class Ea{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 fa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Oi(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=Oi(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,r;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)r=this.manifest[o],!(this.maxAutoQuality&&r.video.height>this.maxAutoQuality)&&(r.bitrate<e&&n>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||w(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:r}=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=()=>{ua(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({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 ma(Jt,jt,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 r=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const $=r&&(!h||h===this.rep);return $||t("Not running!"),$},p=($,k,O)=>{c&&c.abort(),c=Zt(this.urlResolver.resolve($,!1),k,O,()=>this._retryCallback()).withTimeout(jt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Jt).withFinally(()=>{c=null}).send()},f=($,k,O)=>{P(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),k,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=$=>{const k=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${k}=>${$}`),i.playbackRate=$)},E=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const O=ye()-1e4;let W=0;for(let Q=0;Q<this.bufferStates.length;Q++){const A=this.bufferStates[Q];$=Math.min($,A.buf),A.ts<O&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${$} drop=${W} jitter=${this.sourceJitter}`);let G=$-ya;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?b(1.15):G>1?b(1.1):G>.3?b(1.05):b(1)}},R=$=>{let k;const O=()=>k&&k.start?k.start.length:0,W=I=>k.start[I]/1e3,G=I=>k.dur[I]/1e3,Q=I=>k.fragIndex+I,A=(I,ee)=>({chunkIdx:Q(I),startTS:W(I),dur:G(I),discontinuity:ee}),F=()=>{let I=0;if(k&&k.dur){let ee=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,he=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=ee;this.sourceJitter>1&&(me+=this.sourceJitter-1);let Ae=k.dur.length-1;for(;Ae>=0&&(me-=k.dur[Ae],!(me<=0));--Ae);I=Math.min(Ae,k.dur.length-1-he),I=Math.max(I,0)}return A(I,!0)},q=I=>{const ee=O();if(!(ee<=0)){if(w(I)){for(let he=0;he<ee;he++)if(W(he)>I)return A(he)}return F()}},ie=I=>{const ee=O(),he=I?I.chunkIdx+1:0,me=he-k.fragIndex;if(!(ee<=0)){if(!I||me<0||me-ee>Ta)return t(`Resync: offset=${me} bChunks=${ee} chunk=`+JSON.stringify(I)),F();if(!(me>=ee))return A(he-k.fragIndex,!1)}},be=(I,ee,he)=>{d&&d.abort(),d=Zt(this.urlResolver.resolve(I,!0,this.lowLatency),ee,he,()=>this._retryCallback()).withTimeout(jt).withRetryCount(Jt).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,ee)=>{be($,he=>{if(!u())return;k=he;const me=!!k.lowLatency;me!==this.lowLatency&&E(me);let Ae=0;for(let tt=0;tt<k.dur.length;++tt)Ae+=k.dur[tt];Ae>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ae/k.dur.length)),s({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,I(q(ee))},()=>this._handleNetworkError())},nextChunk:ie}},N=()=>{r=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:$=>{const{videoElement:k,logger:O}=this.params;let W=R(e.jidxUrl),G,Q,A,F,q=0,ie,be,ve;const I=()=>{ie&&(clearTimeout(ie),ie=void 0);const Z=Math.max(va,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=q+Z,xe=ye(),we=Math.min(1e4,Ee-xe);q=xe;const dt=()=>{d||u()&&W.seek(()=>{u()&&(q=ye(),ee(),I())})};we>0?ie=window.setTimeout(()=>{this.paused?I():dt()},we):dt()},ee=()=>{let Z;for(;Z=W.nextChunk(F);)F=Z,pi(Z);const Ee=W.nextChunk(A);if(Ee){if(A&&Ee.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?I():(N(),this._initPlayerWith(e));return}tt(Ee)}else I()},he=(Z,Ee)=>{if(!u()||!this.sourceBuffer)return;let xe,we,dt;const Be=ze=>{window.setTimeout(()=>{u()&&he(Z,Ee)},ze)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Be(100);else{const ze=ye(),Fe=k.currentTime;!this.paused&&k.buffered.length>1&&be===Fe&&ze-ve>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),be!==Fe&&(be=Fe,ve=ze);const We=this._getBufferSizeSec();if(We>30)O(`Buffered ${We} seconds; delaying appendBuffer`),Be(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:ze,buf:We}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(mt){if(mt.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),dt=this.sourceBuffer.buffered.length,dt!==0&&(xe=this.sourceBuffer.buffered.start(0),we=Fe,we-xe>4&&this.sourceBuffer.remove(xe,we-3)),Be(1e3);else throw mt}}},me=()=>{Q&&G&&(O([`Appending chunk, sz=${Q.byteLength}:`,JSON.stringify(A)]),he(Q,function(){Q=null,ee()}))},Ae=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),tt=Z=>{u()&&f(Ae(Z),(Ee,xe)=>{if(u()){if(xe/=1e3,Q=Ee,A=Z,n=Z.startTS,xe){const we=Math.min(10,Z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}me()}},()=>this._handleNetworkError())},pi=Z=>{u()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ae(Z),!1)))},Gt=Z=>{u()&&(e.cachedHeader=Z,he(Z,()=>{G=!0,me()}))};r=!0,W.seek(Z=>{if(u()){if(q=ye(),!Z){I();return}F=Z,!J($)||Z.startTS>$?tt(Z):(A=Z,ee())}},$),e.cachedHeader?Gt(e.cachedHeader):p(e.headerUrl,Gt,()=>this._handleNetworkError())},stop:N,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),w(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,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return w(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let p,f,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(f=this._getBufferSizeSec(),b=u/this.bitrate,f>10&&b>.8||f>15&&b>.5||f>20&&b>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}p=this._selectQuality(u),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${u}`)},r=(()=>({updateChunk:(p,f)=>{const b=ye();if(this.chunkRateEstimator.addInterval(p,b,f)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:b-p,speed:v}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=r.get();if(u&&o&&this.autoQuality){if(c&&u>o&&cs(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,p)=>{const f=r.updateChunk(u,p);return f&&d(),f},notifySwitch:u=>{const p=ye();u<o&&(n=p),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=Zt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(jt).withRetryCount(Jt).withRetryInterval(ga,Sa).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ot(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,r=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=r(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))},ba))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var U;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(U||(U={}));const $a=[U.PAUSED,U.PLAYING,U.READY],ka=[U.PAUSED,U.PLAYING,U.READY];class Aa{subscription=new te;video;videoState=new ne(U.STOPPED);dash;representations$=new m([]);textTracksManager=new Ge;droppedFramesManager=new ui;maxSeekBackTime$=new m(1/0);zeroTime$=new m(void 0);liveOffset=new ci;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})};B(this.videoState.stateChangeStarted$.pipe(y(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(y(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(s)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=et(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(y(s=>s.map(({track:r})=>r)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(U.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ce(),y(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(_e({zeroTime:this.zeroTime$.pipe(K(w)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:r})=>this.params.output.liveTime$.next(s+r*1e3),t)).add(ft(this.video,this.params.desiredState.isLooped,t)).add(Xe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(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 r=s&&Ls(s);this.dash.setMaxAutoQuality(r),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case U.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case U.MANIFEST_READY:case U.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case U.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case U.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return M(s.to)}},t)).add(B(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,$e(["init"])).pipe(Ie(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),Ze(this.video)}createLiveDashPlayer(){const e=new Ea({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&&w(t)?t:kt(e.map(({track:c})=>c),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id,r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((r&&s||s!==n)&&this.setVideoTrack(s),o&&this.setAutoQuality(i),r||o||s!==n){const c=e.find(({track:d})=>d.id===s)?.representation;P(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e)?.representation;P(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===U.PAUSED,r=-e,n=r<=this.maxSeekBackTime$.getValue()?r:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ne(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 r=s.name??s.index.toString(10),n=Ht(s.name)??pt(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:r,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===U.MANIFEST_READY&&this.videoState.setState(U.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),w(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(U.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ka.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==l.PAUSED&&r.state===H.Requested&&$a.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_READY),this.dash.attachSource(Ne(this.params.source.url));return;case U.MANIFEST_READY:this.videoState.startTransitionTo(U.READY),this.prepare();break;case U.READY:if(i===l.PAUSED)this.videoState.setState(U.PAUSED);else if(i===l.PLAYING){this.videoState.startTransitionTo(U.PLAYING);const c=s?.from;c&&c===l.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)})}return;case U.PLAYING:i===l.PAUSED&&(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case U.PAUSED:if(i===l.PLAYING)if(this.videoState.startTransitionTo(U.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(U.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(Ne(this.params.source.url,c))}return;default:return M(e)}}}var us=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?Ft.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},rt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,r=a.end(i)*1e3;s<=e&&e<=r&&(t=r)}return Math.max(t-e,0)};const wa=a=>{const e=document.createElement("a");return e.href=a,e.origin},Pa=a=>{const e=document.createElement("a");return e.href=a,e.host};class hs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,r,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=r,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(Pa(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 si{_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 r=0;for(let n=0,o=s.length;n<o;n++)r+=s.end(n)-s.start(n);r&&(this._maxBufferDuration=Math.round(r))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,r,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,p=0;const f=E=>{s(si._str2ua(E.substr(c))),c=E.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=vt(b)),this._lastXhr=new hs(b,e.failoverHosts,E=>{this._lastXhr=void 0,f(E);const v=Date.now()-d;this._params.onBandwidthChange({size:E.length,duration:v,speed:8*E.length/(v/1e3)}),this._onDashCallback("loading",{size:E.length,done:!0}),r?.()},E=>{if(E.length-c>o&&f(E),u===0){u=Date.now();return}p=E.length-h;const v=Date.now()-u;p>=100*1024&&v>=1e3&&(this._params.onBandwidthChange({size:p,duration:v,speed:8*p/(v/1e3)}),p=0,h=E.length,u=Date.now()),this._onDashCallback("loading",{size:E.length,done:!1})},n,(E,v,R)=>this._params.onError(E,v,R))})}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=si._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 Da{_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),r=s?.[1]==="-"?-1:1,n={years:i(s?.[2],r),months:i(s?.[3],r),weeks:i(s?.[4],r),days:i(s?.[5],r),hours:i(s?.[6],r),minutes:i(s?.[7],r),seconds:i(s?.[8],r)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=vt(i)),new hs(i,t,s=>{this.attachManifest(s,t,wa(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,r,n)=>this._params.onError(s,r,n))}attachManifest(e,t,i){const r=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(r,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(r.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),p=h&&h.getElementsByTagName("Initialization")[0],f=p&&n(p,"range").split("-");if(!f||!u){const g=d.parentElement;if(g?.getAttribute("contentType")==="text"){const $=d.getAttribute("id")??void 0,k=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,O=g.getAttribute("lang")??void 0;k&&c.push({id:$,url:k,language:O})}return}const b=.1,E=Number(d.attributes.getNamedItem("bandwidth")?.value),v=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let R;const N=d.attributes.getNamedItem("frameRate")?.value??void 0;R=N?Di(N):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:E,baseURL:v,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(f[0]),initTo:Number(f[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:R,bufferSize:b*E/8,bufferLength:b,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 p=document.createElement("track");u&&p.setAttribute("src",u),d&&p.setAttribute("id",d),h&&p.setAttribute("srclang",h),this._video.appendChild(p)}),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 r=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,r);const n=new DataView(s.buffer);r+=12;const o=n.getUint32(r+4,!1);r+=8;let c=n.getUint32(r,!1),d=n.getUint32(r+4,!1)+(e.indexTo+1);r+=8;const h=n.getUint16(r+2,!1);r+=4,e.refs=[];for(let p=0;p<h;p+=1){const f=d+(n.getUint32(r,!1)&2147483647),b=c+n.getUint32(r+4,!1);r+=12,e.refs.push({fromTime:c/o,toTime:b/o,fromOffset:d,toOffset:f-1}),d=f,c=b}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,r;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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const h=this._appendVector[String(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}u=f.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),r!==f.to&&(r=f.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(f);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},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 si({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 r=this._findRef(t);if(r){if(i){this._isLastRef(r)&&t>=r.toTime&&(t=r.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||r===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:r.fromTime}this._appendVector[String(r.fromTime)]=e,this._stream.load(e,r.fromOffset,r.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=r.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 r=.1;if(s.toTime<i.to+r){const n=this._findRef(s.toTime);n&&n.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,n.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,(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||J(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 r=t[s];if(r.fromTime<=e&&r.toTime>e)return r;r.fromTime>e&&(!i||r.fromTime<i.fromTime)&&(i=r)}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(a){a.STOPPED="stopped",a.MANIFEST_LOADED="manifest-loaded",a.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",a.METADATA_LOADED="metadata-loaded",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const _a=[z.PAUSED,z.PLAYING];class xa{videoState=new ne(z.STOPPED);subscription=new te;video;buffer;dash;representations$=new m([]);currentRepresentation$=new m(void 0);params;textTracksManager=new Ge;droppedFramesManager=new ui;elementSize$=new m(void 0);dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),B(this.videoState.stateChangeStarted$.pipe(y(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(y(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Ke(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ia(this.video),this.dash=new Da({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},r=et(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(r.seeking$.subscribe(()=>{J(this.params.desiredState.seekState.getState().state!==H.Applying)&&(this.videoState.getState()===z.PLAYING||this.videoState.getState()===z.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(Xe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(nt(this.video,t.playbackRate,r.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$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(y(o=>o.map(({track:c})=>c)))}),n(ii(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)})).add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING)},i)).add(r.loadedMetadata$.subscribe(()=>{this.videoState.setState(z.METADATA_LOADED)},i)).add(r.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(y(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(B(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$,C(this.video,"progress")).pipe(y(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),f=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let b;if(!f&&w(h))b=h;else{const E=rt(this.video.buffered,this.video.currentTime*1e3),v=f?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,R=Math.min(E/v,1);b=kt(c.map(({track:g})=>g),{container:p,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:R,playbackRate:this.video.playbackRate,current:c.find(({representation:g})=>g===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const N=t.autoVideoTrackLimits.getTransition();N&&e.autoVideoTrackLimits$.next(N.to)}return w(b)?c.find(({track:E})=>E.id===b)?.representation:void 0}),ce()).subscribe(this.currentRepresentation$,i)).add(_e({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(K(o=>o.to===z.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(K(w))}).pipe(le()).subscribe(()=>this.videoState.setState(z.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(K(w),ce((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=rt(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(ke(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=us(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(le(),yt(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(w)).subscribe(this.handleRepresentationPlay,i)).add(B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(Ie(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),Ze(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 M(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const r=s.name??s.id??s.height.toString(10),n=(s.name&&Ht(s.name))??pt(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:r,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 r of t){const n=r.id||`${r.language}_${Date.now()}`;s.push({id:n,type:"internal",url:r.url||"",language:r.language,isAuto:r.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.id))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return P(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(){ot(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.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(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.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),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(s?.to!==l.PAUSED&&r.state===H.Requested&&_a.includes(e)&&this.seek(r.position,r.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===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case z.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return M(e)}}}var Se;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Se||(Se={}));var ai;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ai||(ai={}));var Ce;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Ce||(Ce={}));var j;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(j||(j={}));var Et;(function(a){a.MP4="mp4",a.WEBM="webm"})(Et||(Et={}));var ri;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(ri||(ri={}));var oe;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(oe||(oe={}));class Fi{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,r=i.length;s<r;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,r=i.length;s<r;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 ls extends Fi{constructor(){super(),this.listeners||Fi.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 ps=class{constructor(){Object.defineProperty(this,"signal",{value:new ls,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&&(ps.prototype[Symbol.toStringTag]="AbortController",ls.prototype[Symbol.toStringTag]="AbortSignal");function fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ra(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=a;if(!fs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=function(d,h){let u;h&&h.signal&&(u=h.signal,delete h.signal);const p=new t(d,h);return u&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),p},r.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const h=r&&r.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 p=new Promise((f,b)=>{h.addEventListener("abort",()=>b(u),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([p,n(c,d)])}return n(c,d)},Request:r}}const hi=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ms=hi?Ra({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Vt=hi?ms.fetch:window.fetch;hi?ms.Request:window.Request;const Tt=hi?ps:window.AbortController;var $i=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const La=(a,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-s-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},Ca=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Vi=Ca?La:window.requestIdleCallback;let gs=!1;try{gs=wi().browser===rs.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Ia{bufferFull$=new x;error$=new x;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 r={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let i;gs&&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:M(t)}}}var Ui=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class qe{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 Ss extends qe{}class Ba extends qe{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 Ma extends qe{parseChildrenBoxes(){return At(this.content)}}class Na extends qe{data;constructor(e){super(e),this.data=this.content}}class Yt extends qe{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Oa extends Yt{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,r=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:r,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class Fa extends qe{parseChildrenBoxes(){return At(this.content)}}class Va extends qe{parseChildrenBoxes(){return At(this.content)}}var lt;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(lt||(lt={}));class Ua extends Yt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=lt.MONOSCOPIC;break;case 1:this.stereoMode=lt.TOP_BOTTOM;break;case 2:this.stereoMode=lt.LEFT_RIGHT;break;case 3:this.stereoMode=lt.STEREO_CUSTOM;break;case 4:this.stereoMode=lt.RIGHT_LEFT;break}this.cursor+=1}}class Ha extends Yt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Ya extends Yt{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 Ga extends qe{parseChildrenBoxes(){return At(this.content)}}class qa extends Yt{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 za extends qe{parseChildrenBoxes(){return At(this.content)}}class Wa extends qe{parseChildrenBoxes(){return At(this.content)}}const Qa={ftyp:Ba,moov:Ma,mdat:Na,sidx:Oa,trak:Fa,mdia:Ga,tkhd:qa,minf:za,sv3d:Va,st3d:Ua,prhd:Ha,proj:Wa,equi:Ya,unknown:Ss};class ja{createBox(e,t){const i=Qa[e];return i?new i(t):new Ss(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return li.createBox(i,new DataView(e.buffer,e.byteOffset))}}const li=new ja;function It(a,e){const t=new TextDecoder("ascii");let i=a.byteOffset,s=[];for(;i<a.byteLength;){const r=t.decode(new DataView(a.buffer,i,1));if(r===e[s.length]?s.push(r):s=[],s.length===4&&s.join("")===e){const o=new DataView(a.buffer,i-7,4).getUint32(0);return i-7+o>a.byteLength?null:li.createBox(e,new DataView(a.buffer,i-7))}i++}return null}function Ja(a,e){const t=[];let i=0;for(;i<a.byteLength;){const s=It(new DataView(a.buffer,a.byteOffset+i,a.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function At(a){const e=[];let t=0;for(;t<a.byteLength;){const i=li.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Xa=new TextDecoder("ascii"),Ka=a=>Xa.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Za=a=>{const e=li.createFromView(a);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(r=>{if(r.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=r.subsegmentDuration/e.timescale*1e3,o={status:j.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+r.referencedSize-1}};return t+=n,i+=r.referencedSize,o})},er=a=>{const e=Ja(a,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(a.buffer,a.byteOffset,t)}return null},tr=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ri.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(It(a,"sv3d")){e.is3dVideo=!0;const i=It(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=It(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const r=It(a,"equi");r&&(e.projectionData.bounds.top=r.projectionBoundsTop,e.projectionData.bounds.right=r.projectionBoundsRight,e.projectionData.bounds.bottom=r.projectionBoundsBottom,e.projectionData.bounds.left=r.projectionBoundsLeft)}return e},ir={validateData:Ka,parseInit:tr,getIndexRange:()=>{},parseSegments:Za,parseFeedableSegmentChunk:er};var T;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(T||(T={}));var _;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(_||(_={}));const Hi={[T.EBML]:{type:_.Master},[T.EBMLVersion]:{type:_.UnsignedInteger},[T.EBMLReadVersion]:{type:_.UnsignedInteger},[T.EBMLMaxIDLength]:{type:_.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[T.DocType]:{type:_.String},[T.DocTypeVersion]:{type:_.UnsignedInteger},[T.DocTypeReadVersion]:{type:_.UnsignedInteger},[T.Void]:{type:_.Binary},[T.Segment]:{type:_.Master},[T.SeekHead]:{type:_.Master},[T.Seek]:{type:_.Master},[T.SeekID]:{type:_.Binary},[T.SeekPosition]:{type:_.UnsignedInteger},[T.Info]:{type:_.Master},[T.TimestampScale]:{type:_.UnsignedInteger},[T.Duration]:{type:_.Float},[T.Tracks]:{type:_.Master},[T.TrackEntry]:{type:_.Master},[T.Video]:{type:_.Master},[T.Projection]:{type:_.Master},[T.ProjectionType]:{type:_.UnsignedInteger},[T.ProjectionPrivate]:{type:_.Master},[T.Chapters]:{type:_.Master},[T.Cluster]:{type:_.Master},[T.Timestamp]:{type:_.UnsignedInteger},[T.SilentTracks]:{type:_.Master},[T.SilentTrackNumber]:{type:_.UnsignedInteger},[T.Position]:{type:_.UnsignedInteger},[T.PrevSize]:{type:_.UnsignedInteger},[T.SimpleBlock]:{type:_.Binary},[T.BlockGroup]:{type:_.Master},[T.EncryptedBlock]:{type:_.Binary},[T.Attachments]:{type:_.Master},[T.Tags]:{type:_.Master},[T.Cues]:{type:_.Master},[T.CuePoint]:{type:_.Master},[T.CueTime]:{type:_.UnsignedInteger},[T.CueTrackPositions]:{type:_.Master},[T.CueTrack]:{type:_.UnsignedInteger},[T.CueClusterPosition]:{type:_.UnsignedInteger},[T.CueRelativePosition]:{type:_.UnsignedInteger},[T.CueDuration]:{type:_.UnsignedInteger},[T.CueBlockNumber]:{type:_.UnsignedInteger},[T.CueCodecState]:{type:_.UnsignedInteger},[T.CueReference]:{type:_.Master},[T.CueRefTime]:{type:_.UnsignedInteger}},bs=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=ni(a,t),s=i in Hi,r=s?Hi[i].type:_.Binary,n=a.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(a.buffer,a.byteOffset+t+1,o-1),d=n&255>>o,h=ni(c),u=d*2**((o-1)*8)+h,p=t+o;let f;return p+u>a.byteLength?f=new DataView(a.buffer,a.byteOffset+p):f=new DataView(a.buffer,a.byteOffset+p,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:r,tagHeaderSize:p,tagSize:p+u,value:f,valueSize:u}},ni=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(a,e)=>{switch(e){case _.SignedInteger:return a.getInt8(0);case _.UnsignedInteger:return ni(a);case _.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(a);case _.UTF8:return new TextDecoder("utf-8").decode(a);case _.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case _.Master:return a;case _.Binary:return a;default:M(e)}},$t=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=bs(i);if(!e(s))return;s.type===_.Master&&$t(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},sr=a=>{if(a.getUint32(0)!==T.EBML)return!1;let e,t,i;const s=bs(a);return $t(s.value,({tag:r,type:n,value:o})=>(r===T.EBMLReadVersion?e=He(o,n):r===T.DocType?t=He(o,n):r===T.DocTypeReadVersion&&(i=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ts=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],ar=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],rr=a=>{let e,t,i,s,r=!1,n=!1,o=!1,c,d,h=!1;const u=0;return $t(a,({tag:p,type:f,value:b,valueSize:E})=>{if(p===T.SeekID){const v=He(b,f);d=ni(v)}else p!==T.SeekPosition&&(d=void 0);return p===T.Segment?(e=b.byteOffset,t=b.byteOffset+E):p===T.Info?r=!0:p===T.SeekHead?n=!0:p===T.TimestampScale?i=He(b,f):p===T.Duration?s=He(b,f):p===T.SeekPosition&&d===T.Cues?c=He(b,f):p===T.Tracks?$t(b,({tag:v,type:R,value:N})=>v===T.ProjectionType?(h=He(N,R)===1,!1):!0):r&&n&&Ts.includes(p)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(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:ri.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nr=a=>{if(J(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},or=(a,e)=>{let t=!1,i=!1;const s=o=>w(o.time)&&w(o.position),r=[];let n;return $t(a,({tag:o,type:c,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&s(n)&&r.push(n),n={};break;case T.CueTime:n&&(n.time=He(d,c));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=He(d,c));break;default:t&&Ts.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&r.push(n),r.map((o,c)=>{const{time:d,position:h}=o,u=r[c+1];return{status:j.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}}})},dr=a=>{let e=0,t=!1;try{$t(a,i=>i.tag===T.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ar.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},cr={validateData:sr,parseInit:rr,getIndexRange:nr,parseSegments:or,parseFeedableSegmentChunk:dr},ys=1e4,ur=3e4,hr=5e3,lr=ys,pr=({id:a,width:e,height:t,bitrate:i,fps:s,quality:r})=>{const n=(r?Ht(r):void 0)??pt({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},fr=({id:a,bitrate:e})=>({id:a,bitrate:e}),mr=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},gr=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),Xt=a=>{const e=[];let t=0,i=a.length-1;for(;t<ys&&i>=0;)e.unshift(a[i]),t+=a[i].time.to-a[i].time.from,i--;return e};class Yi{onLastSegment$=new m(!1);fullyBuffered$=new m(!1);playingRepresentation$=new m(void 0);playingRepresentationInit$=new m(void 0);error$=new x;gaps=[];isSeekingLive=!1;subscription=new te;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:r,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1,manifest:d}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!d?.dynamic,this.container=i,i){case Et.MP4:this.containerParser=ir;break;case Et.WEBM:this.containerParser=cr;break;default:M(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=De(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);P(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ia(this.sourceBuffer),this.subscription.add(C(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(C(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,Ui(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),r=this.parsedInitData.get(t.id);P(i,"No init buffer for starting representation"),P(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(r))}.bind(this));switchTo=De(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);P(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(J(s)||J(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),P(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 r=this.getCurrentPosition();w(r)&&(this.searchGaps(i,t),this.maintain(r))}.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(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=rt(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(r=u)}if(isFinite(this.bufferLimit)&&Ui(this.sourceBuffer.buffered)>=this.bufferLimit){const d=rt(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,r),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===j.FED&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===j.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;w(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=De(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=Xt(d.segmentReference.segments);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);P(i);const s=Xt(i.segmentReference.segments),r=this.initData.get(i.id);if(P(r,"No init buffer for starting representation"),P(s,"No segments for starting representation"),!(r 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(r,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:j.NONE,size:void 0})),s=this.segments.get(t.id)??[],r=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.round(r)>=Math.round(o.time.from)&&Math.round(r)<=Math.round(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=Xt(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(r=>r.time.from<=e&&r.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:p,to:f}},b)=>{const E=p<=i&&f>=i,v=p>i||E||b===0&&i===0,R=Math.min(this.forwardBufferTarget,this.bufferLimit),N=this.preloadOnly&&p<=i+R||f<=i+R;return(u===j.NONE||u===j.PARTIALLY_EJECTED&&v&&N&&this.sourceBuffer&&!$i(this.sourceBuffer.buffered,i))&&v&&N});if(s===-1)return[];if(t!==Ce.BYTE_RANGE)return e.slice(s,s+1);const r=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<r.length&&(n<=d||o<=h);u++){const p=r[u];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status===j.NONE||p.status===j.PARTIALLY_EJECTED)c.push(p);else break}return c}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,r,n=e;const{type:o}=t.segmentReference;switch(o){case Ce.BYTE_RANGE:{s=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Ce.TEMPLATE:{const d=e.at(0);s=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:M(o)}for(const d of n)d.status=j.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await De(c,async function*(){const d=Li(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:r,onProgress:(d,h)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,r?r.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&&w(i)&&(t=rt(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,r){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=j.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const f of this.segments.get(p.id)??[])f.status===j.FED&&f.time.from===u.segment.time.from&&f.time.to===u.segment.time.to&&(f.status=j.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:p}=u,f=d===Ce.BYTE_RANGE,b=f?p.byte.to-p.byte.from+1:h;if(u.representationId!==t||!(!f||p.byte.from>=i&&p.byte.to<i+e.byteLength))continue;if(r.aborted){n();continue}const v=f?p.byte.from-i:0,R=f?p.byte.to-i:e.byteLength,N=v<s,g=R<=s;if(p.status===j.DOWNLOADING&&N&&g){p.status=j.DOWNLOADED,this.activeSegments.delete(u);const $=new DataView(e.buffer,e.byteOffset+v,b);this.sourceBufferTaskQueue.append($,r).then(k=>k&&!r.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&N&&(u.loadedBytes=Math.min(b,s-v),u.loadedBytes>u.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+v+u.feedingBytes,u.loadedBytes-u.feedingBytes),k=u.loadedBytes===b?$:this.containerParser.parseFeedableSegmentChunk($);k?.byteLength&&(p.status=j.PARTIALLY_FED,u.feedingBytes+=k.byteLength,this.sourceBufferTaskQueue.append(k,r).then(O=>{if(r.aborted)n();else if(O)u.fedBytes+=k.byteLength,u.fedBytes===b&&o(u);else{if(u.feedingBytes<b)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.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,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Vi(()=>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?De(this.destroyAbortController.signal,async function*(){const o=Li(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?Xt(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||J(e)||this.sourceBuffer.updating)return!1;let s=0,r=1/0,n=-1/0,o=!1;const c=d=>{r=Math.min(r,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===j.FED&&c(h)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=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===j.FED&&c(h)}}if(o=isFinite(r)&&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 p of this.segments.values())for(const f of p)if(f.status===j.NONE&&Math.round(f.time.from)<=Math.round(h)&&Math.round(f.time.to)>=Math.round(u)){r=h,n=u;break}}if(o=isFinite(r)&&isFinite(n),!o&&i){s=0,r=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===j.FED&&c(u)}return o=isFinite(r)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(r,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 r=0;r<this.sourceBuffer.buffered.length;r++){const n=this.sourceBuffer.buffered.start(r)*1e3,o=this.sourceBuffer.buffered.end(r)*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(r=>s&&r.from===s.from&&r.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Vi(()=>{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(J(this.sourceBuffer)||J(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),r=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:r})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:r}=s;if(r!==j.FED&&r!==j.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=j.PARTIALLY_EJECTED:s.status=j.NONE)}}}var bt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(bt||(bt={}));class Sr{throughputEstimator;requestQuic;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);abortAllController=new Tt;subscription=new te;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}=us(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=De(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=vt(t));const i=yield Vt(t,{signal:this.abortAllController.signal}).catch(Rt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=De(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?bt.HEADER:bt.PARAM,range:i,onProgress:s,priority:r="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(i)switch(t){case bt.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case bt.PARAM:{const A=new URL(c,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),c=A.toString();break}default:M(t)}this.requestQuic&&(c=vt(c));let h=this.abortAllController.signal,u;if(n){const A=new Tt;if(u=B(C(this.abortAllController.signal,"abort"),C(n,"abort")).subscribe(()=>{try{A.abort()}catch(F){Rt(F)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(F){Rt(F)}h=A.signal}const p=ue(),f=yield Vt(c,{priority:r,headers:d,signal:h}).catch(Rt),b=ue();if(this.throughputEstimator?.addRawRtt(b-p),!f)return u?.unsubscribe(),null;if(!f.ok||!f.body)return u?.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const E=parseInt(f.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!E){const A=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(A.byteLength,ue()-b),s?.(new DataView(A),A.byteLength),u?.unsubscribe(),A}if(!s&&!o)return u?.unsubscribe(),f.arrayBuffer();const[v,R]=f.body.tee(),N=v.getReader();o&&this.throughputEstimator?.trackStream(R);let g=0;const $=new ArrayBuffer(E),k=new Uint8Array($),O=new DataView($);let W=!1;const G=A=>{u?.unsubscribe(),W=!0,Rt(A)},Q=De(h,async function*({done:A,value:F}){if(g===0&&this.lastRequestFirstBytes$.next(ue()-p),h.aborted){u?.unsubscribe();return}!A&&F&&(k.set(F,g),g+=F.byteLength,s?.(O,g),yield N?.read().then(Q,G))}.bind(this));return yield N?.read().then(Q,G),u?.unsubscribe(),W?null:$}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ce.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ce.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:M(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=De(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ce.BYTE_RANGE)return null;const{from:s,to:r}=e.initRange;let n=s,o=r,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=r+1===d,c&&(n=Math.min(d,s),o=Math.max(h,r))),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 p=new DataView(u,s-n,r-n+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),b=e.indexRange??t.getIndexRange(f);if(!b)throw new ReferenceError("No way to load representation index");let E;if(c)E=new DataView(u,b.from-n,b.to-b.from+1);else{const R=yield this.fetch(e.url,{range:b,priority:i,measureThroughput:!1});if(!R)return null;E=new DataView(R)}const v=t.parseSegments(E,f,b);return{init:f,dataView:new DataView(u),segments:v}}.bind(this));fetchTemplateRepresentation=De(this.abortAllController.signal,async function*(e,t){if(e.type!==Ce.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:j.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const Rt=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},Gi=a=>{if(!a.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(a),s=i?.[1]==="-"?-1:1,r={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},bi=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,r]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>J(r)?o:J(c)?r:r.padStart(parseInt(c,10),"0"))}return t},br=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},r=i.children[0],n=r.getElementsByTagName("Period")[0],o=n.children,c=r.getAttribute("type")==="dynamic",d=r.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const p=r.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),E=r.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)u=Gi(p);else if(f){const g=Gi(f);w(g)&&(u=g)}else E&&(u=parseInt(E,10));let v=0;const R=r.getAttribute("profiles")?.split(",")??[],N=R.includes(ai.WEBM_AS_IN_FFMPEG)||R.includes(ai.WEBM_AS_IN_SPEC)?Et.WEBM:Et.MP4;for(const g of o){const $=g.getAttribute("mimeType"),k=g.getAttribute("codecs"),O=g.getAttribute("contentType")??$?.split("/")[0],W=g.getAttribute("profiles")?.split(",")??[],G=g.querySelectorAll("Representation"),Q=g.querySelector("SegmentTemplate");if(O===Se.TEXT){for(const A of G){const F=A.getAttribute("id")||"",q=g.getAttribute("lang"),ie=A.querySelector("BaseURL")?.textContent?.trim()??"",be=new URL(ie,e).toString(),ve=F.includes("_auto");s[Se.TEXT].push({id:F,lang:q,isAuto:ve,kind:Se.TEXT,url:be})}continue}for(const A of G){const F=A.getAttribute("mimeType")??$,q=A.getAttribute("codecs")??k??"",ie=A.getAttribute("contentType")??F?.split("/")[0]??O,be=g.getAttribute("profiles")?.split(",")??[],ve=parseInt(A.getAttribute("width")??"",10),I=parseInt(A.getAttribute("height")??"",10),ee=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,he=A.getAttribute("frameRate")??"",me=A.getAttribute("quality")??void 0,Ae=he?Di(he):void 0,tt=A.getAttribute("id")??(v++).toString(10),pi=ie==="video"?`${I}p`:ie==="audio"?`${ee}Kbps`:q,Gt=`${tt}@${pi}`,Z=A.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(Z,e).toString(),xe=[...R,...W,...be];let we;const dt=A.querySelector("SegmentBase"),Be=A.querySelector("SegmentTemplate")??Q;if(dt){const Fe=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[We,mt]=Fe.split("-").map(gt=>parseInt(gt,10)),wt={from:We,to:mt},Pt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[fi,qt]=Pt?Pt.split("-").map(gt=>parseInt(gt,10)):[],Dt=Pt?{from:fi,to:qt}:void 0;we={type:Ce.BYTE_RANGE,url:Ee,initRange:wt,indexRange:Dt}}else if(Be){const Fe={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},We=parseInt(Be.getAttribute("timescale")??"",10),mt=Be.getAttribute("initialization")??"",wt=Be.getAttribute("media"),Pt=parseInt(Be.getAttribute("startNumber")??"",10)??1,fi=bi(mt,Fe);if(!wt)throw new ReferenceError("No media attribute in SegmentTemplate");const qt=Be.querySelectorAll("SegmentTimeline S")??[],Dt=[];let gt=0;if(qt.length){let mi=Pt,Qe=0;for(const _t of qt){const it=parseInt(_t.getAttribute("d")??"",10),ct=parseInt(_t.getAttribute("r")??"",10)||0,zt=parseInt(_t.getAttribute("t")??"",10);Qe=Number.isFinite(zt)?zt:Qe;const gi=it/We*1e3,xi=Qe/We*1e3;for(let Wt=0;Wt<ct+1;Wt++){const Ds=bi(wt,{...Fe,segmentNumber:mi.toString(10),segmentTime:(Qe+Wt*it).toString(10)}),Ri=(xi||0)+Wt*gi,_s=Ri+gi;mi++,Dt.push({time:{from:Ri,to:_s},url:Ds})}Qe+=(ct+1)*it,gt+=(ct+1)*gi}}else if(w(u)){const Qe=parseInt(Be.getAttribute("duration")??"",10)/We*1e3,_t=Math.ceil(u/Qe);let it=0;for(let ct=1;ct<_t;ct++){const zt=bi(wt,{...Fe,segmentNumber:ct.toString(10),segmentTime:it.toString(10)});Dt.push({time:{from:it,to:it+Qe},url:zt}),it+=Qe}}we={type:Ce.TEMPLATE,baseUrl:Ee,initUrl:fi,totalSegmentsDurationMs:gt,segments:Dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!F)continue;const ze={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[ie];ze&&s[ze].push({id:Gt,kind:ze,segmentReference:we,profiles:xe,duration:u,bitrate:ee,mime:F,codecs:q,width:ve,height:I,fps:Ae,quality:me})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:N,representations:s}},ki=1e3,qi=["timeupdate","progress","play","seeked","stalled","waiting"];var Le;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Le||(Le={}));let Tr=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new te;representationSubscription=new te;fetcher;state$=new ne(Le.NONE);currentVideoRepresentation$=new m(void 0);currentVideoRepresentationInit$=new m(void 0);error$=new x;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 x;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Tt;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Sr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=De(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Ne(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=De(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=br(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:r,codecs:n})=>!!(this.element?.canPlayType?.(r)&&window.MediaSource?.isTypeSupported?.(`${r}; codecs="${n}"`)||s===Se.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,r])=>[s,r.filter(i)]))}}.bind(this));async seekLive(e){P(this.element),this.manifestUrlString=Ne(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=De(this.destroyController.signal,async function*(e,t){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Le.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Yi(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],w(t)&&(this.audioBufferManager=new Yi(Se.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(ti(ki).subscribe(n=>{if(this.element?.paused){const o=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ne(this.manifestUrlString,o+1e3,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(B(...qi.map(n=>C(this.element,n))).pipe(Cs(ki),y(n=>this.element?rt(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=>{P(this.element);const c=this.element.playbackRate,d=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),h=ur*c,u=lr*c,p=hr*c;n=o>n?o:n;const f=d===0&&o<p,b=d!==0&&o<h+p&&o>=h,E=d!==0&&o<h;if(E||b){const v=n-(h+u),R=Math.trunc(d+v/c);let N;o?R>0?N=R:N=0:N=d,this.manifestUrlString=Ne(this.manifestUrlString,N,fe.DASH_CMAF_OFFSET_P)}(f||E||b)&&(await this.updateLive(),n=0)}))}const s=B(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(y(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),r=B(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(y(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(B(this.forceEnded$,_e({allBuffersFull:s,someBufferEnded:r}).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(B(...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))),w(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&w(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){P(this.element),this.state$.setState(Le.RUNNING),this.subscription.add(B(...qi.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&$i(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e]?.switchTo(t)}seek(e,t){P(this.element),P(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),$i(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Le.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=ti(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 r of s.gaps)s.playingRepresentation$.getValue()===r.representation&&r.from<=t&&r.to>t&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?i.push(1/0):i.push(r.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 yr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class vr{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,r=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:r,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 Er=`#define GLSLIFY 1
29
+ `}),A}return d?.recordSwitch(G),G};var ke=a=>new URL(a).hostname;const ca=300,ii=(a,e=ca)=>new di(t=>{const{width:i,height:s}=a.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const r=new ResizeObserver(Ns(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),w(c)&&w(d)&&t.next({width:c,height:d})},e));return r.observe(a),()=>r.disconnect()});class ui{onDroopedVideoFramesLimit$=new x;subscription=new te;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new x;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(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=ti(this.droppedFramesChecker.checkTime).pipe(K(()=>this.playing),K(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Ie(this.droppedFramesChecker.checkTime)),i=B(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&&!Ot(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,r=1-(i-s)/i;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&Bt(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])=>Kt(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 xt={};var Y;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));const pe=(a,e)=>new di(t=>{const i=s=>t.next(s);return a.on(e,i),()=>a.off(e,i)});class Mi{subscription=new te;videoState=new ne(Y.DOWNLOADING_LIB);video;player;params;textTracksManager=new Ge;droppedFramesManager=new ui;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 ci;constructor(e){this.video=Ke(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(ke(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||(xt.MediaPlayer=s.MediaPlayer,xt.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(xt.MediaPlayer,"dashjs not loaded"),P(xt.Debug,"dashjs not loaded"),this.player=xt.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?Di(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Js(this.player),Ws(this.player),this.params.tuning.requestQuick&&js(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:g})},s=(g,$)=>this.subscription.add(g.subscribe($,i));s(ii(this.video),this.elementSize$),s(pe(this.player,"error").pipe(y(g=>{const $=typeof g.error=="object"?g.error.code:g.error,k=typeof g.error=="object"?g.error.message:void 0;return{id:`DashJS#${$}`,message:k}})),e.error$),s(pe(this.player,"playbackError").pipe(y(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const r=pe(this.player,"qualityChangeRendered").pipe(K(({mediaType:g})=>g==="video"),y(({newQuality:g})=>this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g)?.track));r.pipe(K(w)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(K(({to:g})=>g===Y.STREAM_INITIALIZED),le()).subscribe(()=>{this.subscription.add(Oe(t.videoTrack,()=>{const g=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g)?.track?.id},g=>{if(J(g))return;const $=this.videoTracks$.getValue().find(({track:k})=>k.id===g)?.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:r.pipe(y(g=>g?.id)),onError:i}))},i)),this.subscription.add(Oe(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,g=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:g}}}}),{onError:i})),s(pe(this.player,"bufferStateChanged").pipe(K(({mediaType:g})=>g==="video"),y(({state:g})=>g==="bufferStalled")),e.isBuffering$),s(pe(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:$}})=>{const k=this.player.getDashMetrics(),O=k.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),W=k.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type")??Ft.HTTP1,G={1:!0,0:!1}[O]??void 0;this.params.output.httpConnectionType$.next(W),this.params.output.httpConnectionReused$.next(G),e.hostname$.next(ke($))}),s(pe(this.player,"streamInitialized"),({streamInfo:{duration:g,manifestInfo:{isDynamic:$,availableFrom:k}}})=>{this.isLive$.next($),this.availableFrom$.next(k.getTime()),$||e.duration$.next(g);const O=[],W=this.player.getQualityFor("video");let G;for(const Q of this.player.getBitrateInfoListFor("video")){const A=Q.qualityIndex.toString(10),F=pt(Q),q=Q.bitrate/1e3,ie={width:Q.width,height:Q.height},be=this.frameRatesByFrameHeight[Q.height];if(F){const ve={id:A,quality:F,bitrate:q,size:ie,fps:be};O.push({track:ve,bitrateInfo:Q}),Q.qualityIndex===W&&(G=ve)}}this.videoTracks$.next(O),e.availableVideoTracks$.next(O.map(({track:Q})=>Q)),G&&e.currentVideoTrack$.next(G),this.videoState.setState(Y.STREAM_INITIALIZED),this.videoState.startTransitionTo(Y.READY)}),s(pe(this.player,"fragmentLoadingCompleted"),({request:g})=>{if(!g.requestEndDate||!g.firstByteDate||!g.bytesLoaded)return;const $=g.requestEndDate.getTime()-g.firstByteDate.getTime(),k=g.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(k,$)}),s(B(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(),$=kt(this.videoTracks$.getValue().map(({track:W})=>W),{container:this.elementSize$.getValue(),throughput:g,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),k=t.autoVideoTrackLimits.getTransition();k&&e.autoVideoTrackLimits$.next(k.to);const O=this.videoTracks$.getValue().find(({track:W})=>W===$);O?.bitrateInfo&&this.player.setQualityFor("video",O?.bitrateInfo.qualityIndex,!1)}),s(_e({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(K(w))}).pipe(K(({isLive:g})=>g),y(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const n=pe(this.player,"playbackTimeUpdated").pipe(y(({time:g})=>g??0));s(_e({availableFrom:this.availableFrom$.pipe(K(w)),currentTime:n}),({availableFrom:g,currentTime:$})=>this.params.output.liveTime$.next(g+$*1e3)),s(n.pipe(K(()=>this.isLive$.getValue()===!1)),e.position$),s(pe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(pe(this.player,"playbackEnded"),e.endedEvent$),s(pe(this.player,"playbackProgress").pipe(y(()=>ds(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(pe(this.player,"playbackPlaying"),()=>{this.videoState.setState(Y.PLAYING),D(t.playbackState,l.PLAYING)}),s(pe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Y.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(pe(this.player,"playbackPaused"),()=>{this.videoState.setState(Y.PAUSED),D(t.playbackState,l.PAUSED)}),s(pe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY)}),s(this.isLive$,e.isLive$),s(ii(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(Ie(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=Qs(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(le()),e.firstBytesEvent$),s(pe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(_e({isLive:this.isLive$,isShort:e.duration$.pipe(y(g=>g<60))}),({isLive:g,isShort:$})=>{const k=!g&&$;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:k}}})}),s(n.pipe(K(g=>g>this.params.tuning.insufficientBufferRuleMargin),le()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(pe(this.player,"manifestLoaded").pipe(le()).subscribe(()=>{this.subscription.add(pe(this.player,"playbackPlaying").pipe(le(),yt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(pe(this.player,"manifestLoaded"),g=>{if(g.data?.Period?.AdaptationSet){const $=[];for(const k of g.data?.Period?.AdaptationSet)if(k.contentType==="text"){const O=k.Representation?.id,W=new URL(k.Representation?.BaseURL,g.data?.baseUri).toString(),G="internal",Q=k.lang;$.push({id:O,url:W,type:G,language:Q})}t.internalTextTracks.startTransitionTo($)}}),this.subscription.add(ft(this.video,t.isLooped,i));const{volumeState$:p,looped$:f,playbackRateState$:b,inPiP$:E,inFullscreen$:v,pause$:R,playing$:N}=et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:N,pause$:R,tracks$:this.videoTracks$.pipe(y(g=>g.map(({track:$})=>$)))}),this.subscription.add(Xe(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(nt(this.video,t.playbackRate,b,i)),this.subscription.add(E.subscribe(e.inPiP$)),this.subscription.add(v.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(Y.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Y.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=Ne(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(Y.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Y.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(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===Y.DOWNLOADING_LIB||e===Y.STREAM_INITIALIZED))switch(i?.to!==l.PAUSED&&s.state===H.Requested&&e!==Y.STOPPED&&t!==l.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case l.STOPPED:{switch(e){case Y.STOPPED:break;case Y.PLAYING:case Y.PAUSED:case Y.READY:this.stop();break;default:M(e)}break}case l.READY:{switch(e){case Y.STOPPED:this.prepare();break;case Y.PLAYING:case Y.PAUSED:case Y.READY:break;default:M(e)}break}case l.PLAYING:{switch(e){case Y.PLAYING:break;case Y.PAUSED:r&&(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 Y.READY:this.play();break;case Y.STOPPED:this.prepare();break;default:M(e)}break}case l.PAUSED:{switch(e){case Y.PLAYING:this.pause(),this.liveOffset.pause();break;case Y.PAUSED:break;case Y.READY:this.videoState.setState(Y.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED);break;case Y.STOPPED:this.prepare();break;default:M(e)}break}default:M(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}Ze(this.video),this.params.output.element$.next(void 0)}}var Ht=a=>{switch(a){case"mobile":return Re.Q_144P;case"lowest":return Re.Q_240P;case"low":return Re.Q_360P;case"sd":case"medium":return Re.Q_480P;case"hd":case"high":return Re.Q_720P;case"fullhd":case"full":return Re.Q_1080P;case"quadhd":case"quad":return Re.Q_1440P;case"ultrahd":case"ultra":return Re.Q_2160P}};const Ni=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var ot=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!Ni(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return Ni(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function ye(){return ue()}function cs(a){return ye()-a}function Oi(a){const e=a.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 ua(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Zt(a,e,t,i){const s=window.XMLHttpRequest;let r,n,o,c=!1,d=0,h,u,p=!1,f="arraybuffer",b=7e3,E=2e3,v=()=>{if(c)return;P(h);const q=cs(h);let ie;if(q<E){ie=E-q,setTimeout(v,ie);return}E*=2,E>b&&(E=b),n&&n.abort(),n=new s,O()};const R=q=>(r=q,F),N=q=>(u=q,F),g=()=>(f="json",F),$=()=>{if(!c){if(--d>=0){v(),i&&i();return}c=!0,u&&u(),t&&t()}},k=q=>(p=q,F),O=()=>{h=ye(),n=new s,n.open("get",a);let q=0,ie,be=0;const ve=()=>(P(h),Math.max(h,Math.max(ie||0,be||0)));if(r&&n.addEventListener("progress",I=>{const ee=ye();r.updateChunk&&I.loaded>q&&(r.updateChunk(ve(),I.loaded-q),q=I.loaded,ie=ee)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(c)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&r){const ee=n.response.byteLength-q;ee&&r.updateChunk&&r.updateChunk(ve(),ee)}u&&u(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),p){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(be=ye(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),F},F={withBitrateReporting:R,withParallel:k,withJSONResponse:g,withRetryCount:q=>(d=q,F),withRetryInterval:(q,ie)=>(w(q)&&(E=q),w(ie)&&(b=ie),F),withTimeout:q=>(o=q,F),withFinally:N,send:O,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return F}const ha=100,la=2e3,pa=500;let fa=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-pa;if(t-e>la){let i=0,s=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)i+=r.end-r.start,s+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;i+=n;const c=r.bytes*n/o;s+=c,r.start=t,r.bytes-=c}}}if(s>0&&i>0){const r=s*8/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/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>ha&&(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 ma{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}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=ye(),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)},r=c=>{e._complete=1,e._responseData=c,e._downloadTime=ye()-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=Zt(t,r,()=>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=ye()}_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=ye();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 r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=r._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)),r._finallyCB&&r._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(r,e)}},r._cb=t,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=n=>(r._finallyCB=n,r),r}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 jt=1e4,Jt=3,ga=300,Sa=2e3,ba=6e4,Ta=10,ya=1,va=500;class Ea{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 fa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Oi(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=Oi(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,r;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)r=this.manifest[o],!(this.maxAutoQuality&&r.video.height>this.maxAutoQuality)&&(r.bitrate<e&&n>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||w(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:r}=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=()=>{ua(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({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 ma(Jt,jt,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 r=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const $=r&&(!h||h===this.rep);return $||t("Not running!"),$},p=($,k,O)=>{c&&c.abort(),c=Zt(this.urlResolver.resolve($,!1),k,O,()=>this._retryCallback()).withTimeout(jt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Jt).withFinally(()=>{c=null}).send()},f=($,k,O)=>{P(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),k,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=$=>{const k=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${k}=>${$}`),i.playbackRate=$)},E=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const O=ye()-1e4;let W=0;for(let Q=0;Q<this.bufferStates.length;Q++){const A=this.bufferStates[Q];$=Math.min($,A.buf),A.ts<O&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${$} drop=${W} jitter=${this.sourceJitter}`);let G=$-ya;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?b(1.15):G>1?b(1.1):G>.3?b(1.05):b(1)}},R=$=>{let k;const O=()=>k&&k.start?k.start.length:0,W=I=>k.start[I]/1e3,G=I=>k.dur[I]/1e3,Q=I=>k.fragIndex+I,A=(I,ee)=>({chunkIdx:Q(I),startTS:W(I),dur:G(I),discontinuity:ee}),F=()=>{let I=0;if(k&&k.dur){let ee=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,he=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=ee;this.sourceJitter>1&&(me+=this.sourceJitter-1);let Ae=k.dur.length-1;for(;Ae>=0&&(me-=k.dur[Ae],!(me<=0));--Ae);I=Math.min(Ae,k.dur.length-1-he),I=Math.max(I,0)}return A(I,!0)},q=I=>{const ee=O();if(!(ee<=0)){if(w(I)){for(let he=0;he<ee;he++)if(W(he)>I)return A(he)}return F()}},ie=I=>{const ee=O(),he=I?I.chunkIdx+1:0,me=he-k.fragIndex;if(!(ee<=0)){if(!I||me<0||me-ee>Ta)return t(`Resync: offset=${me} bChunks=${ee} chunk=`+JSON.stringify(I)),F();if(!(me>=ee))return A(he-k.fragIndex,!1)}},be=(I,ee,he)=>{d&&d.abort(),d=Zt(this.urlResolver.resolve(I,!0,this.lowLatency),ee,he,()=>this._retryCallback()).withTimeout(jt).withRetryCount(Jt).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,ee)=>{be($,he=>{if(!u())return;k=he;const me=!!k.lowLatency;me!==this.lowLatency&&E(me);let Ae=0;for(let tt=0;tt<k.dur.length;++tt)Ae+=k.dur[tt];Ae>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ae/k.dur.length)),s({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,I(q(ee))},()=>this._handleNetworkError())},nextChunk:ie}},N=()=>{r=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:$=>{const{videoElement:k,logger:O}=this.params;let W=R(e.jidxUrl),G,Q,A,F,q=0,ie,be,ve;const I=()=>{ie&&(clearTimeout(ie),ie=void 0);const Z=Math.max(va,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=q+Z,xe=ye(),we=Math.min(1e4,Ee-xe);q=xe;const dt=()=>{d||u()&&W.seek(()=>{u()&&(q=ye(),ee(),I())})};we>0?ie=window.setTimeout(()=>{this.paused?I():dt()},we):dt()},ee=()=>{let Z;for(;Z=W.nextChunk(F);)F=Z,pi(Z);const Ee=W.nextChunk(A);if(Ee){if(A&&Ee.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?I():(N(),this._initPlayerWith(e));return}tt(Ee)}else I()},he=(Z,Ee)=>{if(!u()||!this.sourceBuffer)return;let xe,we,dt;const Be=ze=>{window.setTimeout(()=>{u()&&he(Z,Ee)},ze)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Be(100);else{const ze=ye(),Fe=k.currentTime;!this.paused&&k.buffered.length>1&&be===Fe&&ze-ve>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),be!==Fe&&(be=Fe,ve=ze);const We=this._getBufferSizeSec();if(We>30)O(`Buffered ${We} seconds; delaying appendBuffer`),Be(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:ze,buf:We}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(mt){if(mt.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),dt=this.sourceBuffer.buffered.length,dt!==0&&(xe=this.sourceBuffer.buffered.start(0),we=Fe,we-xe>4&&this.sourceBuffer.remove(xe,we-3)),Be(1e3);else throw mt}}},me=()=>{Q&&G&&(O([`Appending chunk, sz=${Q.byteLength}:`,JSON.stringify(A)]),he(Q,function(){Q=null,ee()}))},Ae=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),tt=Z=>{u()&&f(Ae(Z),(Ee,xe)=>{if(u()){if(xe/=1e3,Q=Ee,A=Z,n=Z.startTS,xe){const we=Math.min(10,Z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}me()}},()=>this._handleNetworkError())},pi=Z=>{u()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ae(Z),!1)))},Gt=Z=>{u()&&(e.cachedHeader=Z,he(Z,()=>{G=!0,me()}))};r=!0,W.seek(Z=>{if(u()){if(q=ye(),!Z){I();return}F=Z,!J($)||Z.startTS>$?tt(Z):(A=Z,ee())}},$),e.cachedHeader?Gt(e.cachedHeader):p(e.headerUrl,Gt,()=>this._handleNetworkError())},stop:N,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),w(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,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return w(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let p,f,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(f=this._getBufferSizeSec(),b=u/this.bitrate,f>10&&b>.8||f>15&&b>.5||f>20&&b>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}p=this._selectQuality(u),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${u}`)},r=(()=>({updateChunk:(p,f)=>{const b=ye();if(this.chunkRateEstimator.addInterval(p,b,f)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:b-p,speed:v}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=r.get();if(u&&o&&this.autoQuality){if(c&&u>o&&cs(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,p)=>{const f=r.updateChunk(u,p);return f&&d(),f},notifySwitch:u=>{const p=ye();u<o&&(n=p),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=Zt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(jt).withRetryCount(Jt).withRetryInterval(ga,Sa).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ot(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,r=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=r(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))},ba))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var U;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(U||(U={}));const $a=[U.PAUSED,U.PLAYING,U.READY],ka=[U.PAUSED,U.PLAYING,U.READY];class Aa{subscription=new te;video;videoState=new ne(U.STOPPED);dash;representations$=new m([]);textTracksManager=new Ge;droppedFramesManager=new ui;maxSeekBackTime$=new m(1/0);zeroTime$=new m(void 0);liveOffset=new ci;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})};B(this.videoState.stateChangeStarted$.pipe(y(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(y(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(s)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=et(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(y(s=>s.map(({track:r})=>r)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(U.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ce(),y(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(_e({zeroTime:this.zeroTime$.pipe(K(w)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:r})=>this.params.output.liveTime$.next(s+r*1e3),t)).add(ft(this.video,this.params.desiredState.isLooped,t)).add(Xe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(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 r=s&&Ls(s);this.dash.setMaxAutoQuality(r),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case U.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case U.MANIFEST_READY:case U.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case U.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case U.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return M(s.to)}},t)).add(B(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,$e(["init"])).pipe(Ie(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),Ze(this.video)}createLiveDashPlayer(){const e=new Ea({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&&w(t)?t:kt(e.map(({track:c})=>c),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id,r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((r&&s||s!==n)&&this.setVideoTrack(s),o&&this.setAutoQuality(i),r||o||s!==n){const c=e.find(({track:d})=>d.id===s)?.representation;P(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e)?.representation;P(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===U.PAUSED,r=-e,n=r<=this.maxSeekBackTime$.getValue()?r:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ne(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 r=s.name??s.index.toString(10),n=Ht(s.name)??pt(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:r,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===U.MANIFEST_READY&&this.videoState.setState(U.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),w(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(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(U.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ka.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==l.PAUSED&&r.state===H.Requested&&$a.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_READY),this.dash.attachSource(Ne(this.params.source.url));return;case U.MANIFEST_READY:this.videoState.startTransitionTo(U.READY),this.prepare();break;case U.READY:if(i===l.PAUSED)this.videoState.setState(U.PAUSED);else if(i===l.PLAYING){this.videoState.startTransitionTo(U.PLAYING);const c=s?.from;c&&c===l.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)})}return;case U.PLAYING:i===l.PAUSED&&(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case U.PAUSED:if(i===l.PLAYING)if(this.videoState.startTransitionTo(U.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(U.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(Ne(this.params.source.url,c))}return;default:return M(e)}}}var us=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?Ft.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},rt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,r=a.end(i)*1e3;s<=e&&e<=r&&(t=r)}return Math.max(t-e,0)};const wa=a=>{const e=document.createElement("a");return e.href=a,e.origin},Pa=a=>{const e=document.createElement("a");return e.href=a,e.host};class hs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,r,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=r,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(Pa(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 si{_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 r=0;for(let n=0,o=s.length;n<o;n++)r+=s.end(n)-s.start(n);r&&(this._maxBufferDuration=Math.round(r))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,r,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,p=0;const f=E=>{s(si._str2ua(E.substr(c))),c=E.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=vt(b)),this._lastXhr=new hs(b,e.failoverHosts,E=>{this._lastXhr=void 0,f(E);const v=Date.now()-d;this._params.onBandwidthChange({size:E.length,duration:v,speed:8*E.length/(v/1e3)}),this._onDashCallback("loading",{size:E.length,done:!0}),r?.()},E=>{if(E.length-c>o&&f(E),u===0){u=Date.now();return}p=E.length-h;const v=Date.now()-u;p>=100*1024&&v>=1e3&&(this._params.onBandwidthChange({size:p,duration:v,speed:8*p/(v/1e3)}),p=0,h=E.length,u=Date.now()),this._onDashCallback("loading",{size:E.length,done:!1})},n,(E,v,R)=>this._params.onError(E,v,R))})}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=si._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 Da{_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),r=s?.[1]==="-"?-1:1,n={years:i(s?.[2],r),months:i(s?.[3],r),weeks:i(s?.[4],r),days:i(s?.[5],r),hours:i(s?.[6],r),minutes:i(s?.[7],r),seconds:i(s?.[8],r)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=vt(i)),new hs(i,t,s=>{this.attachManifest(s,t,wa(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,r,n)=>this._params.onError(s,r,n))}attachManifest(e,t,i){const r=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(r,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(r.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),p=h&&h.getElementsByTagName("Initialization")[0],f=p&&n(p,"range").split("-");if(!f||!u){const g=d.parentElement;if(g?.getAttribute("contentType")==="text"){const $=d.getAttribute("id")??void 0,k=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,O=g.getAttribute("lang")??void 0;k&&c.push({id:$,url:k,language:O})}return}const b=.1,E=Number(d.attributes.getNamedItem("bandwidth")?.value),v=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let R;const N=d.attributes.getNamedItem("frameRate")?.value??void 0;R=N?Di(N):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:E,baseURL:v,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(f[0]),initTo:Number(f[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:R,bufferSize:b*E/8,bufferLength:b,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 p=document.createElement("track");u&&p.setAttribute("src",u),d&&p.setAttribute("id",d),h&&p.setAttribute("srclang",h),this._video.appendChild(p)}),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 r=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,r);const n=new DataView(s.buffer);r+=12;const o=n.getUint32(r+4,!1);r+=8;let c=n.getUint32(r,!1),d=n.getUint32(r+4,!1)+(e.indexTo+1);r+=8;const h=n.getUint16(r+2,!1);r+=4,e.refs=[];for(let p=0;p<h;p+=1){const f=d+(n.getUint32(r,!1)&2147483647),b=c+n.getUint32(r+4,!1);r+=12,e.refs.push({fromTime:c/o,toTime:b/o,fromOffset:d,toOffset:f-1}),d=f,c=b}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,r;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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const h=this._appendVector[String(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}u=f.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),r!==f.to&&(r=f.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(f);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},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 si({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 r=this._findRef(t);if(r){if(i){this._isLastRef(r)&&t>=r.toTime&&(t=r.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||r===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:r.fromTime}this._appendVector[String(r.fromTime)]=e,this._stream.load(e,r.fromOffset,r.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=r.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 r=.1;if(s.toTime<i.to+r){const n=this._findRef(s.toTime);n&&n.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,n.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,(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||J(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 r=t[s];if(r.fromTime<=e&&r.toTime>e)return r;r.fromTime>e&&(!i||r.fromTime<i.fromTime)&&(i=r)}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(a){a.STOPPED="stopped",a.MANIFEST_LOADED="manifest-loaded",a.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",a.METADATA_LOADED="metadata-loaded",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const _a=[z.PAUSED,z.PLAYING];class xa{videoState=new ne(z.STOPPED);subscription=new te;video;buffer;dash;representations$=new m([]);currentRepresentation$=new m(void 0);params;textTracksManager=new Ge;droppedFramesManager=new ui;elementSize$=new m(void 0);dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),B(this.videoState.stateChangeStarted$.pipe(y(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(y(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Ke(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ia(this.video),this.dash=new Da({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},r=et(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(r.seeking$.subscribe(()=>{J(this.params.desiredState.seekState.getState().state!==H.Applying)&&(this.videoState.getState()===z.PLAYING||this.videoState.getState()===z.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(Xe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(nt(this.video,t.playbackRate,r.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$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(y(o=>o.map(({track:c})=>c)))}),n(ii(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)})).add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING)},i)).add(r.loadedMetadata$.subscribe(()=>{this.videoState.setState(z.METADATA_LOADED)},i)).add(r.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(y(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(B(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$,C(this.video,"progress")).pipe(y(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),f=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let b;if(!f&&w(h))b=h;else{const E=rt(this.video.buffered,this.video.currentTime*1e3),v=f?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,R=Math.min(E/v,1);b=kt(c.map(({track:g})=>g),{container:p,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:R,playbackRate:this.video.playbackRate,current:c.find(({representation:g})=>g===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const N=t.autoVideoTrackLimits.getTransition();N&&e.autoVideoTrackLimits$.next(N.to)}return w(b)?c.find(({track:E})=>E.id===b)?.representation:void 0}),ce()).subscribe(this.currentRepresentation$,i)).add(_e({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(K(o=>o.to===z.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(K(w))}).pipe(le()).subscribe(()=>this.videoState.setState(z.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(K(w),ce((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=rt(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(ke(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=us(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(le(),yt(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(w)).subscribe(this.handleRepresentationPlay,i)).add(B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(Ie(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),Ze(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 M(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const r=s.name??s.id??s.height.toString(10),n=(s.name&&Ht(s.name))??pt(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:r,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 r of t){const n=r.id||`${r.language}_${Date.now()}`;s.push({id:n,type:"internal",url:r.url||"",language:r.language,isAuto:r.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.id))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return P(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(){ot(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.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(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.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),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(s?.to!==l.PAUSED&&r.state===H.Requested&&_a.includes(e)&&this.seek(r.position,r.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===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case z.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return M(e)}}}var Se;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Se||(Se={}));var ai;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ai||(ai={}));var Ce;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Ce||(Ce={}));var j;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(j||(j={}));var Et;(function(a){a.MP4="mp4",a.WEBM="webm"})(Et||(Et={}));var ri;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(ri||(ri={}));var oe;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(oe||(oe={}));class Fi{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,r=i.length;s<r;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,r=i.length;s<r;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 ls extends Fi{constructor(){super(),this.listeners||Fi.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 ps=class{constructor(){Object.defineProperty(this,"signal",{value:new ls,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&&(ps.prototype[Symbol.toStringTag]="AbortController",ls.prototype[Symbol.toStringTag]="AbortSignal");function fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ra(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=a;if(!fs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=function(d,h){let u;h&&h.signal&&(u=h.signal,delete h.signal);const p=new t(d,h);return u&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),p},r.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const h=r&&r.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 p=new Promise((f,b)=>{h.addEventListener("abort",()=>b(u),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([p,n(c,d)])}return n(c,d)},Request:r}}const hi=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ms=hi?Ra({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Vt=hi?ms.fetch:window.fetch;hi?ms.Request:window.Request;const Tt=hi?ps:window.AbortController;var $i=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const La=(a,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-s-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},Ca=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Vi=Ca?La:window.requestIdleCallback;let gs=!1;try{gs=wi().browser===rs.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Ia{bufferFull$=new x;error$=new x;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 r={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let i;gs&&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:M(t)}}}var Ui=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class qe{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 Ss extends qe{}class Ba extends qe{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 Ma extends qe{parseChildrenBoxes(){return At(this.content)}}class Na extends qe{data;constructor(e){super(e),this.data=this.content}}class Yt extends qe{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Oa extends Yt{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,r=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:r,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class Fa extends qe{parseChildrenBoxes(){return At(this.content)}}class Va extends qe{parseChildrenBoxes(){return At(this.content)}}var lt;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(lt||(lt={}));class Ua extends Yt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=lt.MONOSCOPIC;break;case 1:this.stereoMode=lt.TOP_BOTTOM;break;case 2:this.stereoMode=lt.LEFT_RIGHT;break;case 3:this.stereoMode=lt.STEREO_CUSTOM;break;case 4:this.stereoMode=lt.RIGHT_LEFT;break}this.cursor+=1}}class Ha extends Yt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Ya extends Yt{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 Ga extends qe{parseChildrenBoxes(){return At(this.content)}}class qa extends Yt{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 za extends qe{parseChildrenBoxes(){return At(this.content)}}class Wa extends qe{parseChildrenBoxes(){return At(this.content)}}const Qa={ftyp:Ba,moov:Ma,mdat:Na,sidx:Oa,trak:Fa,mdia:Ga,tkhd:qa,minf:za,sv3d:Va,st3d:Ua,prhd:Ha,proj:Wa,equi:Ya,unknown:Ss};class ja{createBox(e,t){const i=Qa[e];return i?new i(t):new Ss(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return li.createBox(i,new DataView(e.buffer,e.byteOffset))}}const li=new ja;function It(a,e){const t=new TextDecoder("ascii");let i=a.byteOffset,s=[];for(;i<a.byteLength;){const r=t.decode(new DataView(a.buffer,i,1));if(r===e[s.length]?s.push(r):s=[],s.length===4&&s.join("")===e){const o=new DataView(a.buffer,i-7,4).getUint32(0);return i-7+o>a.byteLength?null:li.createBox(e,new DataView(a.buffer,i-7))}i++}return null}function Ja(a,e){const t=[];let i=0;for(;i<a.byteLength;){const s=It(new DataView(a.buffer,a.byteOffset+i,a.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function At(a){const e=[];let t=0;for(;t<a.byteLength;){const i=li.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Xa=new TextDecoder("ascii"),Ka=a=>Xa.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Za=a=>{const e=li.createFromView(a);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(r=>{if(r.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=r.subsegmentDuration/e.timescale*1e3,o={status:j.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+r.referencedSize-1}};return t+=n,i+=r.referencedSize,o})},er=a=>{const e=Ja(a,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(a.buffer,a.byteOffset,t)}return null},tr=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ri.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(It(a,"sv3d")){e.is3dVideo=!0;const i=It(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=It(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const r=It(a,"equi");r&&(e.projectionData.bounds.top=r.projectionBoundsTop,e.projectionData.bounds.right=r.projectionBoundsRight,e.projectionData.bounds.bottom=r.projectionBoundsBottom,e.projectionData.bounds.left=r.projectionBoundsLeft)}return e},ir={validateData:Ka,parseInit:tr,getIndexRange:()=>{},parseSegments:Za,parseFeedableSegmentChunk:er};var T;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(T||(T={}));var _;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(_||(_={}));const Hi={[T.EBML]:{type:_.Master},[T.EBMLVersion]:{type:_.UnsignedInteger},[T.EBMLReadVersion]:{type:_.UnsignedInteger},[T.EBMLMaxIDLength]:{type:_.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[T.DocType]:{type:_.String},[T.DocTypeVersion]:{type:_.UnsignedInteger},[T.DocTypeReadVersion]:{type:_.UnsignedInteger},[T.Void]:{type:_.Binary},[T.Segment]:{type:_.Master},[T.SeekHead]:{type:_.Master},[T.Seek]:{type:_.Master},[T.SeekID]:{type:_.Binary},[T.SeekPosition]:{type:_.UnsignedInteger},[T.Info]:{type:_.Master},[T.TimestampScale]:{type:_.UnsignedInteger},[T.Duration]:{type:_.Float},[T.Tracks]:{type:_.Master},[T.TrackEntry]:{type:_.Master},[T.Video]:{type:_.Master},[T.Projection]:{type:_.Master},[T.ProjectionType]:{type:_.UnsignedInteger},[T.ProjectionPrivate]:{type:_.Master},[T.Chapters]:{type:_.Master},[T.Cluster]:{type:_.Master},[T.Timestamp]:{type:_.UnsignedInteger},[T.SilentTracks]:{type:_.Master},[T.SilentTrackNumber]:{type:_.UnsignedInteger},[T.Position]:{type:_.UnsignedInteger},[T.PrevSize]:{type:_.UnsignedInteger},[T.SimpleBlock]:{type:_.Binary},[T.BlockGroup]:{type:_.Master},[T.EncryptedBlock]:{type:_.Binary},[T.Attachments]:{type:_.Master},[T.Tags]:{type:_.Master},[T.Cues]:{type:_.Master},[T.CuePoint]:{type:_.Master},[T.CueTime]:{type:_.UnsignedInteger},[T.CueTrackPositions]:{type:_.Master},[T.CueTrack]:{type:_.UnsignedInteger},[T.CueClusterPosition]:{type:_.UnsignedInteger},[T.CueRelativePosition]:{type:_.UnsignedInteger},[T.CueDuration]:{type:_.UnsignedInteger},[T.CueBlockNumber]:{type:_.UnsignedInteger},[T.CueCodecState]:{type:_.UnsignedInteger},[T.CueReference]:{type:_.Master},[T.CueRefTime]:{type:_.UnsignedInteger}},bs=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=ni(a,t),s=i in Hi,r=s?Hi[i].type:_.Binary,n=a.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(a.buffer,a.byteOffset+t+1,o-1),d=n&255>>o,h=ni(c),u=d*2**((o-1)*8)+h,p=t+o;let f;return p+u>a.byteLength?f=new DataView(a.buffer,a.byteOffset+p):f=new DataView(a.buffer,a.byteOffset+p,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:r,tagHeaderSize:p,tagSize:p+u,value:f,valueSize:u}},ni=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(a,e)=>{switch(e){case _.SignedInteger:return a.getInt8(0);case _.UnsignedInteger:return ni(a);case _.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(a);case _.UTF8:return new TextDecoder("utf-8").decode(a);case _.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case _.Master:return a;case _.Binary:return a;default:M(e)}},$t=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=bs(i);if(!e(s))return;s.type===_.Master&&$t(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},sr=a=>{if(a.getUint32(0)!==T.EBML)return!1;let e,t,i;const s=bs(a);return $t(s.value,({tag:r,type:n,value:o})=>(r===T.EBMLReadVersion?e=He(o,n):r===T.DocType?t=He(o,n):r===T.DocTypeReadVersion&&(i=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ts=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],ar=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],rr=a=>{let e,t,i,s,r=!1,n=!1,o=!1,c,d,h=!1;const u=0;return $t(a,({tag:p,type:f,value:b,valueSize:E})=>{if(p===T.SeekID){const v=He(b,f);d=ni(v)}else p!==T.SeekPosition&&(d=void 0);return p===T.Segment?(e=b.byteOffset,t=b.byteOffset+E):p===T.Info?r=!0:p===T.SeekHead?n=!0:p===T.TimestampScale?i=He(b,f):p===T.Duration?s=He(b,f):p===T.SeekPosition&&d===T.Cues?c=He(b,f):p===T.Tracks?$t(b,({tag:v,type:R,value:N})=>v===T.ProjectionType?(h=He(N,R)===1,!1):!0):r&&n&&Ts.includes(p)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(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:ri.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nr=a=>{if(J(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},or=(a,e)=>{let t=!1,i=!1;const s=o=>w(o.time)&&w(o.position),r=[];let n;return $t(a,({tag:o,type:c,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&s(n)&&r.push(n),n={};break;case T.CueTime:n&&(n.time=He(d,c));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=He(d,c));break;default:t&&Ts.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&r.push(n),r.map((o,c)=>{const{time:d,position:h}=o,u=r[c+1];return{status:j.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}}})},dr=a=>{let e=0,t=!1;try{$t(a,i=>i.tag===T.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ar.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},cr={validateData:sr,parseInit:rr,getIndexRange:nr,parseSegments:or,parseFeedableSegmentChunk:dr},ys=1e4,ur=3e4,hr=5e3,lr=ys,pr=({id:a,width:e,height:t,bitrate:i,fps:s,quality:r})=>{const n=(r?Ht(r):void 0)??pt({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},fr=({id:a,bitrate:e})=>({id:a,bitrate:e}),mr=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},gr=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),Xt=a=>{const e=[];let t=0,i=a.length-1;for(;t<ys&&i>=0;)e.unshift(a[i]),t+=a[i].time.to-a[i].time.from,i--;return e};class Yi{onLastSegment$=new m(!1);fullyBuffered$=new m(!1);playingRepresentation$=new m(void 0);playingRepresentationInit$=new m(void 0);error$=new x;gaps=[];isSeekingLive=!1;subscription=new te;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:r,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1,manifest:d}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!d?.dynamic,this.container=i,i){case Et.MP4:this.containerParser=ir;break;case Et.WEBM:this.containerParser=cr;break;default:M(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=De(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);P(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ia(this.sourceBuffer),this.subscription.add(C(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(C(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,Ui(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),r=this.parsedInitData.get(t.id);P(i,"No init buffer for starting representation"),P(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(r))}.bind(this));switchTo=De(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);P(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(J(s)||J(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),P(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 r=this.getCurrentPosition();w(r)&&(this.searchGaps(i,t),this.maintain(r))}.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(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=rt(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(r=u)}if(isFinite(this.bufferLimit)&&Ui(this.sourceBuffer.buffered)>=this.bufferLimit){const d=rt(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,r),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===j.FED&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===j.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;w(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=De(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=Xt(d.segmentReference.segments);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);P(i);const s=Xt(i.segmentReference.segments),r=this.initData.get(i.id);if(P(r,"No init buffer for starting representation"),P(s,"No segments for starting representation"),!(r 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(r,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:j.NONE,size:void 0})),s=this.segments.get(t.id)??[],r=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.round(r)>=Math.round(o.time.from)&&Math.round(r)<=Math.round(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=Xt(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(r=>r.time.from<=e&&r.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:p,to:f}},b)=>{const E=p<=i&&f>=i,v=p>i||E||b===0&&i===0,R=Math.min(this.forwardBufferTarget,this.bufferLimit),N=this.preloadOnly&&p<=i+R||f<=i+R;return(u===j.NONE||u===j.PARTIALLY_EJECTED&&v&&N&&this.sourceBuffer&&!$i(this.sourceBuffer.buffered,i))&&v&&N});if(s===-1)return[];if(t!==Ce.BYTE_RANGE)return e.slice(s,s+1);const r=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<r.length&&(n<=d||o<=h);u++){const p=r[u];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status===j.NONE||p.status===j.PARTIALLY_EJECTED)c.push(p);else break}return c}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,r,n=e;const{type:o}=t.segmentReference;switch(o){case Ce.BYTE_RANGE:{s=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Ce.TEMPLATE:{const d=e.at(0);s=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:M(o)}for(const d of n)d.status=j.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await De(c,async function*(){const d=Li(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:r,onProgress:(d,h)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,r?r.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&&w(i)&&(t=rt(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,r){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=j.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const f of this.segments.get(p.id)??[])f.status===j.FED&&f.time.from===u.segment.time.from&&f.time.to===u.segment.time.to&&(f.status=j.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:p}=u,f=d===Ce.BYTE_RANGE,b=f?p.byte.to-p.byte.from+1:h;if(u.representationId!==t||!(!f||p.byte.from>=i&&p.byte.to<i+e.byteLength))continue;if(r.aborted){n();continue}const v=f?p.byte.from-i:0,R=f?p.byte.to-i:e.byteLength,N=v<s,g=R<=s;if(p.status===j.DOWNLOADING&&N&&g){p.status=j.DOWNLOADED,this.activeSegments.delete(u);const $=new DataView(e.buffer,e.byteOffset+v,b);this.sourceBufferTaskQueue.append($,r).then(k=>k&&!r.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&N&&(u.loadedBytes=Math.min(b,s-v),u.loadedBytes>u.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+v+u.feedingBytes,u.loadedBytes-u.feedingBytes),k=u.loadedBytes===b?$:this.containerParser.parseFeedableSegmentChunk($);k?.byteLength&&(p.status=j.PARTIALLY_FED,u.feedingBytes+=k.byteLength,this.sourceBufferTaskQueue.append(k,r).then(O=>{if(r.aborted)n();else if(O)u.fedBytes+=k.byteLength,u.fedBytes===b&&o(u);else{if(u.feedingBytes<b)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.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,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Vi(()=>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?De(this.destroyAbortController.signal,async function*(){const o=Li(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?Xt(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||J(e)||this.sourceBuffer.updating)return!1;let s=0,r=1/0,n=-1/0,o=!1;const c=d=>{r=Math.min(r,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===j.FED&&c(h)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=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===j.FED&&c(h)}}if(o=isFinite(r)&&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 p of this.segments.values())for(const f of p)if(f.status===j.NONE&&Math.round(f.time.from)<=Math.round(h)&&Math.round(f.time.to)>=Math.round(u)){r=h,n=u;break}}if(o=isFinite(r)&&isFinite(n),!o&&i){s=0,r=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===j.FED&&c(u)}return o=isFinite(r)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(r,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 r=0;r<this.sourceBuffer.buffered.length;r++){const n=this.sourceBuffer.buffered.start(r)*1e3,o=this.sourceBuffer.buffered.end(r)*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(r=>s&&r.from===s.from&&r.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Vi(()=>{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(J(this.sourceBuffer)||J(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),r=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:r})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:r}=s;if(r!==j.FED&&r!==j.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=j.PARTIALLY_EJECTED:s.status=j.NONE)}}}var bt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(bt||(bt={}));class Sr{throughputEstimator;requestQuic;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);abortAllController=new Tt;subscription=new te;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}=us(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=De(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=vt(t));const i=yield Vt(t,{signal:this.abortAllController.signal}).catch(Rt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=De(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?bt.HEADER:bt.PARAM,range:i,onProgress:s,priority:r="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(i)switch(t){case bt.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case bt.PARAM:{const A=new URL(c,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),c=A.toString();break}default:M(t)}this.requestQuic&&(c=vt(c));let h=this.abortAllController.signal,u;if(n){const A=new Tt;if(u=B(C(this.abortAllController.signal,"abort"),C(n,"abort")).subscribe(()=>{try{A.abort()}catch(F){Rt(F)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(F){Rt(F)}h=A.signal}const p=ue(),f=yield Vt(c,{priority:r,headers:d,signal:h}).catch(Rt),b=ue();if(this.throughputEstimator?.addRawRtt(b-p),!f)return u?.unsubscribe(),null;if(!f.ok||!f.body)return u?.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const E=parseInt(f.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!E){const A=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(A.byteLength,ue()-b),s?.(new DataView(A),A.byteLength),u?.unsubscribe(),A}if(!s&&!o)return u?.unsubscribe(),f.arrayBuffer();const[v,R]=f.body.tee(),N=v.getReader();o&&this.throughputEstimator?.trackStream(R);let g=0;const $=new ArrayBuffer(E),k=new Uint8Array($),O=new DataView($);let W=!1;const G=A=>{u?.unsubscribe(),W=!0,Rt(A)},Q=De(h,async function*({done:A,value:F}){if(g===0&&this.lastRequestFirstBytes$.next(ue()-p),h.aborted){u?.unsubscribe();return}!A&&F&&(k.set(F,g),g+=F.byteLength,s?.(O,g),yield N?.read().then(Q,G))}.bind(this));return yield N?.read().then(Q,G),u?.unsubscribe(),W?null:$}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ce.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ce.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:M(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=De(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ce.BYTE_RANGE)return null;const{from:s,to:r}=e.initRange;let n=s,o=r,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=r+1===d,c&&(n=Math.min(d,s),o=Math.max(h,r))),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 p=new DataView(u,s-n,r-n+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),b=e.indexRange??t.getIndexRange(f);if(!b)throw new ReferenceError("No way to load representation index");let E;if(c)E=new DataView(u,b.from-n,b.to-b.from+1);else{const R=yield this.fetch(e.url,{range:b,priority:i,measureThroughput:!1});if(!R)return null;E=new DataView(R)}const v=t.parseSegments(E,f,b);return{init:f,dataView:new DataView(u),segments:v}}.bind(this));fetchTemplateRepresentation=De(this.abortAllController.signal,async function*(e,t){if(e.type!==Ce.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:j.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const Rt=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},Gi=a=>{if(!a.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(a),s=i?.[1]==="-"?-1:1,r={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},bi=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,r]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>J(r)?o:J(c)?r:r.padStart(parseInt(c,10),"0"))}return t},br=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},r=i.children[0],n=r.getElementsByTagName("Period")[0],o=n.children,c=r.getAttribute("type")==="dynamic",d=r.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const p=r.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),E=r.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)u=Gi(p);else if(f){const g=Gi(f);w(g)&&(u=g)}else E&&(u=parseInt(E,10));let v=0;const R=r.getAttribute("profiles")?.split(",")??[],N=R.includes(ai.WEBM_AS_IN_FFMPEG)||R.includes(ai.WEBM_AS_IN_SPEC)?Et.WEBM:Et.MP4;for(const g of o){const $=g.getAttribute("mimeType"),k=g.getAttribute("codecs"),O=g.getAttribute("contentType")??$?.split("/")[0],W=g.getAttribute("profiles")?.split(",")??[],G=g.querySelectorAll("Representation"),Q=g.querySelector("SegmentTemplate");if(O===Se.TEXT){for(const A of G){const F=A.getAttribute("id")||"",q=g.getAttribute("lang"),ie=A.querySelector("BaseURL")?.textContent?.trim()??"",be=new URL(ie,e).toString(),ve=F.includes("_auto");s[Se.TEXT].push({id:F,lang:q,isAuto:ve,kind:Se.TEXT,url:be})}continue}for(const A of G){const F=A.getAttribute("mimeType")??$,q=A.getAttribute("codecs")??k??"",ie=A.getAttribute("contentType")??F?.split("/")[0]??O,be=g.getAttribute("profiles")?.split(",")??[],ve=parseInt(A.getAttribute("width")??"",10),I=parseInt(A.getAttribute("height")??"",10),ee=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,he=A.getAttribute("frameRate")??"",me=A.getAttribute("quality")??void 0,Ae=he?Di(he):void 0,tt=A.getAttribute("id")??(v++).toString(10),pi=ie==="video"?`${I}p`:ie==="audio"?`${ee}Kbps`:q,Gt=`${tt}@${pi}`,Z=A.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(Z,e).toString(),xe=[...R,...W,...be];let we;const dt=A.querySelector("SegmentBase"),Be=A.querySelector("SegmentTemplate")??Q;if(dt){const Fe=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[We,mt]=Fe.split("-").map(gt=>parseInt(gt,10)),wt={from:We,to:mt},Pt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[fi,qt]=Pt?Pt.split("-").map(gt=>parseInt(gt,10)):[],Dt=Pt?{from:fi,to:qt}:void 0;we={type:Ce.BYTE_RANGE,url:Ee,initRange:wt,indexRange:Dt}}else if(Be){const Fe={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},We=parseInt(Be.getAttribute("timescale")??"",10),mt=Be.getAttribute("initialization")??"",wt=Be.getAttribute("media"),Pt=parseInt(Be.getAttribute("startNumber")??"",10)??1,fi=bi(mt,Fe);if(!wt)throw new ReferenceError("No media attribute in SegmentTemplate");const qt=Be.querySelectorAll("SegmentTimeline S")??[],Dt=[];let gt=0;if(qt.length){let mi=Pt,Qe=0;for(const _t of qt){const it=parseInt(_t.getAttribute("d")??"",10),ct=parseInt(_t.getAttribute("r")??"",10)||0,zt=parseInt(_t.getAttribute("t")??"",10);Qe=Number.isFinite(zt)?zt:Qe;const gi=it/We*1e3,xi=Qe/We*1e3;for(let Wt=0;Wt<ct+1;Wt++){const Ds=bi(wt,{...Fe,segmentNumber:mi.toString(10),segmentTime:(Qe+Wt*it).toString(10)}),Ri=(xi||0)+Wt*gi,_s=Ri+gi;mi++,Dt.push({time:{from:Ri,to:_s},url:Ds})}Qe+=(ct+1)*it,gt+=(ct+1)*gi}}else if(w(u)){const Qe=parseInt(Be.getAttribute("duration")??"",10)/We*1e3,_t=Math.ceil(u/Qe);let it=0;for(let ct=1;ct<_t;ct++){const zt=bi(wt,{...Fe,segmentNumber:ct.toString(10),segmentTime:it.toString(10)});Dt.push({time:{from:it,to:it+Qe},url:zt}),it+=Qe}}we={type:Ce.TEMPLATE,baseUrl:Ee,initUrl:fi,totalSegmentsDurationMs:gt,segments:Dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!F)continue;const ze={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[ie];ze&&s[ze].push({id:Gt,kind:ze,segmentReference:we,profiles:xe,duration:u,bitrate:ee,mime:F,codecs:q,width:ve,height:I,fps:Ae,quality:me})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:N,representations:s}},ki=1e3,qi=["timeupdate","progress","play","seeked","stalled","waiting"];var Le;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Le||(Le={}));let Tr=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new te;representationSubscription=new te;fetcher;state$=new ne(Le.NONE);currentVideoRepresentation$=new m(void 0);currentVideoRepresentationInit$=new m(void 0);error$=new x;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 x;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Tt;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Sr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=De(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Ne(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=De(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=br(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:r,codecs:n})=>!!(this.element?.canPlayType?.(r)&&window.MediaSource?.isTypeSupported?.(`${r}; codecs="${n}"`)||s===Se.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,r])=>[s,r.filter(i)]))}}.bind(this));async seekLive(e){P(this.element),this.manifestUrlString=Ne(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=De(this.destroyController.signal,async function*(e,t){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Le.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Yi(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],w(t)&&(this.audioBufferManager=new Yi(Se.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(ti(ki).subscribe(n=>{if(this.element?.paused){const o=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ne(this.manifestUrlString,o+1e3,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(B(...qi.map(n=>C(this.element,n))).pipe(Cs(ki),y(n=>this.element?rt(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=>{P(this.element);const c=this.element.playbackRate,d=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),h=ur*c,u=lr*c,p=hr*c;n=o>n?o:n;const f=d===0&&o<p,b=d!==0&&o<h+p&&o>=h,E=d!==0&&o<h;if(E||b){const v=n-(h+u),R=Math.trunc(d+v/c);let N;o?R>0?N=R:N=0:N=d,this.manifestUrlString=Ne(this.manifestUrlString,N,fe.DASH_CMAF_OFFSET_P)}(f||E||b)&&(await this.updateLive(),n=0)}))}const s=B(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(y(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),r=B(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(y(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(B(this.forceEnded$,_e({allBuffersFull:s,someBufferEnded:r}).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(B(...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))),w(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&w(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){P(this.element),this.state$.setState(Le.RUNNING),this.subscription.add(B(...qi.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&$i(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e]?.switchTo(t)}seek(e,t){P(this.element),P(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),$i(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Le.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=ti(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 r of s.gaps)s.playingRepresentation$.getValue()===r.representation&&r.from<=t&&r.to>t&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?i.push(1/0):i.push(r.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 yr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class vr{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,r=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:r,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 Er=`#define GLSLIFY 1
30
30
  attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,$r=`#ifdef GL_ES
31
31
  precision highp float;precision highp int;
32
32
  #else