@vkontakte/videoplayer-core 2.0.98-dev.27a468df.0 → 2.0.98-dev.489417ae.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +13 -13
- package/es2015.esm.js +9 -9
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +14 -14
- package/esnext.cjs.js +8 -8
- package/esnext.esm.js +10 -10
- package/evergreen.esm.js +9 -9
- package/index.d.ts +4 -1
- package/package.json +3 -4
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.98-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.489417ae.0
|
|
3
|
+
* Thu, 15 Feb 2024 17:01:30 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as g,Subject as I,Subscription as se,isNonNullable as P,ErrorCategory as L,isNullable as Y,fromEvent as M,assertNever as N,merge as O,tap as Ii,map as A,observableFrom as Oe,filterChanged as le,assertNonNullable as w,debounce as Qe,getHighestQuality as cr,timeout as ur,getCurrentBrowser as Gi,CurrentClientBrowser as ns,combine as xe,once as be,mapTo as Zt,filter as K,now as ne,assertNotEmptyArray as hr,videoSizeToQuality as It,isInvariantQuality as Ht,isHigher as Kt,isLower as Li,isHigherOrEqual as Ki,isLowerOrEqual as Ns,Observable as zi,interval as Yt,VideoQuality as je,videoQualityToHeight as lr,abortable as oe,getExponentialDelay as gi,throttle as fr,isIOS as pr,CurrentClientDevice as mr,safeStorage as ji,fillWithDefault as gr,Logger as Sr}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as cd,Subject as ud,Subscription as hd,ValueSubject as ld,VideoQuality as fd}from"@vkontakte/videoplayer-shared/esnext.esm.js";import br from"lodash/debounce.js";import{debounce as yr}from"lodash";const Tr="2.0.98-dev.27a468df.0";var f;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(f||(f={}));var y;(function(r){r.MPEG="MPEG",r.DASH="DASH",r.DASH_SEP="DASH_SEP",r.DASH_SEP_VK="DASH_SEP",r.DASH_WEBM="DASH_WEBM",r.DASH_WEBM_AV1="DASH_WEBM_AV1",r.DASH_WEBM_VK="DASH_WEBM",r.DASH_ONDEMAND="DASH_ONDEMAND",r.DASH_ONDEMAND_VK="DASH_ONDEMAND",r.DASH_LIVE="DASH_LIVE",r.DASH_LIVE_CMAF="DASH_LIVE_CMAF",r.DASH_LIVE_WEBM="DASH_LIVE_WEBM",r.HLS="HLS",r.HLS_ONDEMAND="HLS_ONDEMAND",r.HLS_JS="HLS",r.HLS_LIVE="HLS_LIVE",r.HLS_LIVE_CMAF="HLS_LIVE_CMAF",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Be;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(Be||(Be={}));var Le;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(Le||(Le={}));var yi;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(yi||(yi={}));var j;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(j||(j={}));var xt;(function(r){r.NONE="none",r.INLINE="inline",r.FULLSCREEN="fullscreen",r.SECOND_SCREEN="second_screen",r.PIP="pip"})(xt||(xt={}));var vr=r=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Er{connection$=new g(void 0);castState$=new g(Le.NOT_AVAILABLE);errorEvent$=new I;contentId;realCastState$=new g(Le.NOT_AVAILABLE);subscription=new se;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const i=P(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},s||vr("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:L.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){P(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Y(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Y(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(M(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return N(s.sessionState)}})).add(O(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ii(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),A(s=>s.castState)),Oe([i.getCastState()])).pipe(le(),A(kr),Ii(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const a=s===Le.CONNECTED,n=P(this.connection$.getValue());if(a&&!n){const o=i.getCurrentSession();w(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(Y(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===Le.CONNECTED?P(this.connection$.getValue())?Le.CONNECTED:Le.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const kr=r=>{switch(r){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Le.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Le.AVAILABLE;case cast.framework.CastState.CONNECTING:return Le.CONNECTING;case cast.framework.CastState.CONNECTED:return Le.CONNECTED;default:return N(r)}};var fe;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",r[r.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Me=(r,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{const i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:N(t)}return r};const Ci=(r,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:N(e)}};var R=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class de{state;prevState;transition;transitionStarted$=new I;transitionEnded$=new I;transitionUpdated$=new I;forceChanged$=new I;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||P(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const $r=r=>{switch(r){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return N(r)}};var W;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(W||(W={}));const Ar=5,wr=5,Dr=500,ls=7e3;class Pr{subscription=new se;loadMediaTimeoutSubscription=new se;videoState=new de(W.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($r(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new se;this.subscription.add(e),this.subscription.add(O(this.videoState.stateChangeStarted$.pipe(A(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(A(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,a)=>this.subscription.add(s.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new I;e.add(s.pipe(Qe(Dr)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===j.Applying||Math.abs(o-a)>Ar)&&s.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:a}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<wr&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,f.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:N(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:j.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===W.PAUSED||e===W.PLAYING)&&(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===W.PLAYING||e===W.PAUSED)&&(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.params.desiredState.playbackState.getTransition()?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY)}handleRemoteStop(){this.videoState.getState()!==W.STOPPED&&this.videoState.setState(W.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,a;switch(e){case y.MPEG:{const d=t[e];w(d);const h=cr(Object.keys(d));w(h);const u=d[h];w(u),i=u,s="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const d=t[e];w(d),i=d.url,s="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const d=t[e];w(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const d=t[e];w(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const d=t[e];w(d),i=Me(d.url),s="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.VIDEO_PIPELINE,message:d,thrown:h}),h}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return P(o)&&(n.metadata.title=o),P(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===j.Applying||i.state===j.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,a)=>{this.loadMediaTimeoutSubscription.add(ur(ls).subscribe(()=>a(`timeout(${ls})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.VIDEO_PIPELINE,message:a,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.stop());return}if(!t){if(s?.to!==f.PAUSED&&a.state===j.Requested&&e!==W.STOPPED){this.seek(a.position/1e3);return}switch(i){case f.READY:{switch(e){case W.PLAYING:case W.PAUSED:case W.READY:break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PLAYING:{switch(e){case W.PLAYING:break;case W.PAUSED:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.READY:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case W.PLAYING:this.videoState.startTransitionTo(W.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case W.PAUSED:break;case W.READY:this.videoState.startTransitionTo(W.PAUSED),this.videoState.setState(W.PAUSED);break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}default:N(i)}}}}var xr=r=>{let e,t=!1,i=!1;r.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),r.extend("MediaSourceController",function(){const{parent:s}=this,a=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&e?.()}}},!0)},Lr=r=>{const e=new g(1/0),t=new I,i=new g(void 0),s=new g(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const S=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;P(b)&&!isNaN(b)&&e.next(b)}const l=u["x-delivery-type"]??yi.HTTP1,p={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(l),s.next(p)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return r.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(l){if(l.request.type==="MPD"){const p=l.onload,S=l.progress;l.onload=function(...v){return c(this),p(...v)},l.progress=function(...v){return d(this),S(...v)},o()}return u(l)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},Rt=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Rr=r=>r.extend("RequestModifier",()=>({modifyRequestURL:Rt}),!0),Ir=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const at=(r,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:a}={})=>{const n=r.getState(),o=e(),c=Y(s),d=new se;return s&&d.add(s.subscribe(h=>{const u=r.getState();i(h,u)&&r.setState(h)},a)),i(o,n)||(t(n),c&&r.setState(n)),d.add(r.stateChangeStarted$.subscribe(h=>{t(h.to),c&&r.setState(h.to)},a)),d},Ct=(r,e,t)=>at(e,()=>r.loop,i=>{P(i)&&(r.loop=i)},{onError:t}),gt=(r,e,t,i)=>at(e,()=>({muted:r.muted,volume:r.volume}),s=>{P(s)&&(r.muted=s.muted,r.volume=s.volume)},{equal:(s,a)=>s===a||s?.muted===a?.muted&&s?.volume===a?.volume,changed$:t,onError:i}),wt=(r,e,t,i)=>at(e,()=>r.playbackRate,s=>{P(s)&&(r.playbackRate=s)},{changed$:t,onError:i}),Cr=r=>["__",r.language,r.label].join("|"),Br=(r,e)=>{if(r.id===e)return!0;const[t,i,s]=e.split("|");return r.language===i&&r.label===s};class nt{available$=new I;current$=new g(void 0);error$=new I;video;cueSettings;subscription=new se;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=a=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(at(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{P(a)&&this.setInternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(at(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{P(a)&&this.setExternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(at(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:s})),this.subscription.add(at(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){w(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(O(M(e,"addtrack"),M(e,"removetrack"),Oe(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),le((i,s)=>i.length===s.length&&i.every(({id:a},n)=>a===s[n].id))).subscribe(this.available$)),this.subscription.add(O(M(e,"change"),Oe(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),A(i=>i&&this.htmlTextTrackToITextTrack(i).id),le()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(M(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=a=>{const n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(M(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;P(t.align)&&(s.align=t.align),P(t.position)&&(s.position=t.position),P(t.size)&&(s.size=t.size),P(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){w(this.video);const t=[...this.video.textTracks];return e?t:t.filter(nt.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Cr(e),a=this.externalTracks.has(s),n=s.includes("auto");return a?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(s)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:s,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){w(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Y(e)||!Br(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){w(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){w(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const os=r=>{r.removeAttribute("src"),r.load()},_r=r=>{try{r.pause(),r.playbackRate=0,os(r),r.remove()}catch(e){console.error(e)}};class Mr{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 Zi=window.WeakMap?new WeakMap:new Mr,St=r=>{let e=r.querySelector("video");const t=!!e;return e?os(e):(e=document.createElement("video"),r.appendChild(e)),Zi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=r=>{const e=Zi.get(r);Zi.delete(r),e?os(r):_r(r)};class Ei{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 Fs=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},fs=r=>{const e=Fs(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},Or=r=>{const e=Fs(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},es=3;class Nr{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const a=this._source.buffered.end(t);s>e&&s-e<es&&(s=e),this._buffer.push({from:s,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||es))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:a})=>{const n=s>=e&&s<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(s,e):s<e&&a>t?(i(t,a),i(s,e)):i(s,a))})}destroy(){this._buffer=[]}}var Vs=(r,e,t=es)=>{let i=0,s=0;for(let a=0;a<r.length;a++){const n=r.start(a),o=r.end(a);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=a-1;c>=0;c--)r.end(c)+t>=i&&(i=r.start(c));for(let c=a+1;c<r.length;c++)r.start(c)-t<=s&&(s=r.end(c))}}return{from:i,to:s}};const yt=r=>{const e=m=>M(r,m).pipe(Zt(void 0)),i=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>M(r,m))).pipe(A(m=>m.type==="ended"?r.readyState<2:r.readyState<3),le()),s=O(M(r,"progress"),M(r,"timeupdate")).pipe(A(()=>Vs(r.buffered,r.currentTime))),n=Gi().browser===ns.Safari?xe({play:e("play").pipe(be()),playing:e("playing")}).pipe(Zt(void 0)):e("playing"),o=M(r,"volumechange").pipe(A(()=>({muted:r.muted,volume:r.volume}))),c=M(r,"ratechange").pipe(A(()=>r.playbackRate)),d=M(r,"error").pipe(K(()=>!!(r.error||r.played.length)),A(()=>{const m=r.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:r.error??void 0}})),h=M(r,"timeupdate").pipe(A(()=>r.currentTime)),u=new I,l=.3;let p;h.subscribe(m=>{r.loop&&P(p)&&P(m)&&p>=r.duration-l&&m<=l&&u.next(p),p=m});const S=M(r,"enterpictureinpicture"),v=M(r,"leavepictureinpicture"),b=new g(Or(r));S.subscribe(()=>b.next(!0)),v.subscribe(()=>b.next(!1));const D=new g(fs(r));return M(r,"fullscreenchange").pipe(A(()=>fs(r))).subscribe(D),{playing$:n,pause$:e("pause").pipe(K(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:M(r,"durationchange").pipe(A(()=>r.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:b,inFullscreen$:D}},qi=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let ds=!1,$t={};const Fr=r=>{ds=r},Vr=()=>{$t={}},Ur=r=>{r($t)},wi=(r,e)=>{ds&&($t.meta=$t.meta??{},$t.meta[r]=e)};class lt{name;constructor(e){this.name=e}next(e){if(!ds)return;$t.series=$t.series??{};const t=$t.series[this.name]??[];t.push([Date.now(),e]),$t.series[this.name]=t}}var Ft;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(Ft||(Ft={}));const Hr=new lt("best_bitrate"),Yr=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class Us{last;history={};recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Gr='Assertion "ABR Tracks is empty array" failed',Gt=(r,{container:e,throughput:t,tuning:i,limits:s,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{hr(r,Gr);const l=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*i.containerSizeFactor,height:e.height*l*i.containerSizeFactor},S=p&&It(p),v=i.considerPlaybackRate&&P(o)?o:1,b=r.filter(T=>!Ht(T.quality)).sort((T,V)=>Kt(T.quality,V.quality)?-1:1),D=b.at(-1)?.quality,C=b.at(0)?.quality,m=Y(s)||P(s.min)&&P(s.max)&&Li(s.max,s.min)||P(s.min)&&C&&Kt(s.min,C)||P(s.max)&&D&&Li(s.max,D),$=v*Yr(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},q=b.filter(T=>(S?Li(T.quality,S):!0)?(P(t)&&isFinite(t)&&P(T.bitrate)?t-a>=T.bitrate*$:!0)?i.lazyQualitySwitch&&P(i.minBufferToSwitchUp)&&c&&!Ht(c.quality)&&(n??0)<i.minBufferToSwitchUp&&Kt(T.quality,c.quality)?(x[T.quality]=Ft.Buffer,!1):!!h&&Ki(T.quality,h)?(x[T.quality]=Ft.DroppedFramesLimit,!1):m||(Y(s.max)||Ns(T.quality,s.max))&&(Y(s.min)||Ki(T.quality,s.min))?!0:(x[T.quality]=Ft.FitsQualityLimits,!1):(x[T.quality]=Ft.FitsThroughput,!1):(x[T.quality]=Ft.FitsContainer,!1))[0];q&&q.bitrate&&Hr.next(q.bitrate);const F=q??b[Math.ceil((b.length-1)/2)]??r[0];F.quality!==d?.last?.quality&&u({message:`
|
|
6
|
+
import{ValueSubject as m,Subject as I,Subscription as se,isNonNullable as P,ErrorCategory as L,isNullable as Y,fromEvent as M,assertNever as N,merge as O,tap as yi,map as A,observableFrom as Ne,filterChanged as le,assertNonNullable as D,debounce as je,getHighestQuality as cr,timeout as ur,getCurrentBrowser as Gi,CurrentClientBrowser as ns,combine as xe,once as be,mapTo as Zt,filter as K,now as ne,assertNotEmptyArray as hr,videoSizeToQuality as It,isInvariantQuality as Ht,isHigher as Kt,isLower as Ri,isHigherOrEqual as Ki,isLowerOrEqual as Ns,Observable as zi,debounceFn as lr,interval as Yt,VideoQuality as Je,videoQualityToHeight as fr,abortable as oe,getExponentialDelay as gi,throttle as pr,isIOS as mr,CurrentClientDevice as gr,safeStorage as ji,fillWithDefault as Sr,Logger as br}from"@vkontakte/videoplayer-shared/evergreen.esm.js";import{Observable as nd,Subject as od,Subscription as dd,ValueSubject as cd,VideoQuality as ud}from"@vkontakte/videoplayer-shared/evergreen.esm.js";const yr="2.0.98-dev.489417ae.0";var f;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(f||(f={}));var y;(function(r){r.MPEG="MPEG",r.DASH="DASH",r.DASH_SEP="DASH_SEP",r.DASH_SEP_VK="DASH_SEP",r.DASH_WEBM="DASH_WEBM",r.DASH_WEBM_AV1="DASH_WEBM_AV1",r.DASH_WEBM_VK="DASH_WEBM",r.DASH_ONDEMAND="DASH_ONDEMAND",r.DASH_ONDEMAND_VK="DASH_ONDEMAND",r.DASH_LIVE="DASH_LIVE",r.DASH_LIVE_CMAF="DASH_LIVE_CMAF",r.DASH_LIVE_WEBM="DASH_LIVE_WEBM",r.HLS="HLS",r.HLS_ONDEMAND="HLS_ONDEMAND",r.HLS_JS="HLS",r.HLS_LIVE="HLS_LIVE",r.HLS_LIVE_CMAF="HLS_LIVE_CMAF",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var _e;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})(_e||(_e={}));var Re;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(Re||(Re={}));var Ti;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(Ti||(Ti={}));var j;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(j||(j={}));var xt;(function(r){r.NONE="none",r.INLINE="inline",r.FULLSCREEN="fullscreen",r.SECOND_SCREEN="second_screen",r.PIP="pip"})(xt||(xt={}));var Tr=r=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class vr{connection$=new m(void 0);castState$=new m(Re.NOT_AVAILABLE);errorEvent$=new I;contentId;realCastState$=new m(Re.NOT_AVAILABLE);subscription=new se;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const i=P(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},s||Tr("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:L.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){P(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Y(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Y(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(M(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return N(s.sessionState)}})).add(O(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(yi(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),A(s=>s.castState)),Ne([i.getCastState()])).pipe(le(),A(Er),yi(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const a=s===Re.CONNECTED,n=P(this.connection$.getValue());if(a&&!n){const o=i.getCurrentSession();D(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(Y(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===Re.CONNECTED?P(this.connection$.getValue())?Re.CONNECTED:Re.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Er=r=>{switch(r){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Re.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Re.AVAILABLE;case cast.framework.CastState.CONNECTING:return Re.CONNECTING;case cast.framework.CastState.CONNECTED:return Re.CONNECTED;default:return N(r)}};var fe;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",r[r.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Oe=(r,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return r;const i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{const i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:N(t)}return r};const Ci=(r,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:N(e)}};var R=(r,e,t=!1)=>{const i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};class de{state;prevState;transition;transitionStarted$=new I;transitionEnded$=new I;transitionUpdated$=new I;forceChanged$=new I;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||P(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const kr=r=>{switch(r){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return N(r)}};var W;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(W||(W={}));const $r=5,Ar=5,wr=500,ls=7e3;class Dr{subscription=new se;loadMediaTimeoutSubscription=new se;videoState=new de(W.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(kr(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new se;this.subscription.add(e),this.subscription.add(O(this.videoState.stateChangeStarted$.pipe(A(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(A(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,a)=>this.subscription.add(s.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new I;e.add(s.pipe(je(wr)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===j.Applying||Math.abs(o-a)>$r)&&s.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:a}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Ar&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,f.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:N(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:j.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===W.PAUSED||e===W.PLAYING)&&(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===W.PLAYING||e===W.PAUSED)&&(this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.params.desiredState.playbackState.getTransition()?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY)}handleRemoteStop(){this.videoState.getState()!==W.STOPPED&&this.videoState.setState(W.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,a;switch(e){case y.MPEG:{const d=t[e];D(d);const h=cr(Object.keys(d));D(h);const u=d[h];D(u),i=u,s="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const d=t[e];D(d),i=d.url,s="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const d=t[e];D(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const d=t[e];D(d),i=d.url,s="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const d=t[e];D(d),i=Oe(d.url),s="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.VIDEO_PIPELINE,message:d,thrown:h}),h}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return P(o)&&(n.metadata.title=o),P(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===j.Applying||i.state===j.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,a)=>{this.loadMediaTimeoutSubscription.add(ur(ls).subscribe(()=>a(`timeout(${ls})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.VIDEO_PIPELINE,message:a,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.stop());return}if(!t){if(s?.to!==f.PAUSED&&a.state===j.Requested&&e!==W.STOPPED){this.seek(a.position/1e3);return}switch(i){case f.READY:{switch(e){case W.PLAYING:case W.PAUSED:case W.READY:break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PLAYING:{switch(e){case W.PLAYING:break;case W.PAUSED:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.READY:this.videoState.startTransitionTo(W.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case W.PLAYING:this.videoState.startTransitionTo(W.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case W.PAUSED:break;case W.READY:this.videoState.startTransitionTo(W.PAUSED),this.videoState.setState(W.PAUSED);break;case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();break;default:N(e)}break}default:N(i)}}}}var Pr=r=>{let e,t=!1,i=!1;r.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),r.extend("MediaSourceController",function(){const{parent:s}=this,a=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&e?.()}}},!0)},xr=r=>{const e=new m(1/0),t=new I,i=new m(void 0),s=new m(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const S=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;P(b)&&!isNaN(b)&&e.next(b)}const l=u["x-delivery-type"]??Ti.HTTP1,p={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(l),s.next(p)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return r.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(l){if(l.request.type==="MPD"){const p=l.onload,S=l.progress;l.onload=function(...v){return c(this),p(...v)},l.progress=function(...v){return d(this),S(...v)},o()}return u(l)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},Rt=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Lr=r=>r.extend("RequestModifier",()=>({modifyRequestURL:Rt}),!0),Rr=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const at=(r,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:a}={})=>{const n=r.getState(),o=e(),c=Y(s),d=new se;return s&&d.add(s.subscribe(h=>{const u=r.getState();i(h,u)&&r.setState(h)},a)),i(o,n)||(t(n),c&&r.setState(n)),d.add(r.stateChangeStarted$.subscribe(h=>{t(h.to),c&&r.setState(h.to)},a)),d},Ct=(r,e,t)=>at(e,()=>r.loop,i=>{P(i)&&(r.loop=i)},{onError:t}),gt=(r,e,t,i)=>at(e,()=>({muted:r.muted,volume:r.volume}),s=>{P(s)&&(r.muted=s.muted,r.volume=s.volume)},{equal:(s,a)=>s===a||s?.muted===a?.muted&&s?.volume===a?.volume,changed$:t,onError:i}),wt=(r,e,t,i)=>at(e,()=>r.playbackRate,s=>{P(s)&&(r.playbackRate=s)},{changed$:t,onError:i}),Ir=r=>["__",r.language,r.label].join("|"),Cr=(r,e)=>{if(r.id===e)return!0;const[t,i,s]=e.split("|");return r.language===i&&r.label===s};class nt{available$=new I;current$=new m(void 0);error$=new I;video;cueSettings;subscription=new se;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=a=>{this.error$.next({id:"TextTracksManager",category:L.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(at(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{P(a)&&this.setInternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(at(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{P(a)&&this.setExternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(at(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:s})),this.subscription.add(at(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){D(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(O(M(e,"addtrack"),M(e,"removetrack"),Ne(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),le((i,s)=>i.length===s.length&&i.every(({id:a},n)=>a===s[n].id))).subscribe(this.available$)),this.subscription.add(O(M(e,"change"),Ne(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),A(i=>i&&this.htmlTextTrackToITextTrack(i).id),le()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(M(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=a=>{const n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(M(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;P(t.align)&&(s.align=t.align),P(t.position)&&(s.position=t.position),P(t.size)&&(s.size=t.size),P(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){D(this.video);const t=[...this.video.textTracks];return e?t:t.filter(nt.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Ir(e),a=this.externalTracks.has(s),n=s.includes("auto");return a?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(s)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:s,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){D(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Y(e)||!Cr(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){D(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){D(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const os=r=>{r.removeAttribute("src"),r.load()},Br=r=>{try{r.pause(),r.playbackRate=0,os(r),r.remove()}catch(e){console.error(e)}};class _r{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 Zi=window.WeakMap?new WeakMap:new _r,St=r=>{let e=r.querySelector("video");const t=!!e;return e?os(e):(e=document.createElement("video"),r.appendChild(e)),Zi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=r=>{const e=Zi.get(r);Zi.delete(r),e?os(r):Br(r)};class ki{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 Fs=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},fs=r=>{const e=Fs(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},Mr=r=>{const e=Fs(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)},es=3;class Or{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const a=this._source.buffered.end(t);s>e&&s-e<es&&(s=e),this._buffer.push({from:s,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||es))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:a})=>{const n=s>=e&&s<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(s,e):s<e&&a>t?(i(t,a),i(s,e)):i(s,a))})}destroy(){this._buffer=[]}}var Vs=(r,e,t=es)=>{let i=0,s=0;for(let a=0;a<r.length;a++){const n=r.start(a),o=r.end(a);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=a-1;c>=0;c--)r.end(c)+t>=i&&(i=r.start(c));for(let c=a+1;c<r.length;c++)r.start(c)-t<=s&&(s=r.end(c))}}return{from:i,to:s}};const yt=r=>{const e=g=>M(r,g).pipe(Zt(void 0)),i=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>M(r,g))).pipe(A(g=>g.type==="ended"?r.readyState<2:r.readyState<3),le()),s=O(M(r,"progress"),M(r,"timeupdate")).pipe(A(()=>Vs(r.buffered,r.currentTime))),n=Gi().browser===ns.Safari?xe({play:e("play").pipe(be()),playing:e("playing")}).pipe(Zt(void 0)):e("playing"),o=M(r,"volumechange").pipe(A(()=>({muted:r.muted,volume:r.volume}))),c=M(r,"ratechange").pipe(A(()=>r.playbackRate)),d=M(r,"error").pipe(K(()=>!!(r.error||r.played.length)),A(()=>{const g=r.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:r.error??void 0}})),h=M(r,"timeupdate").pipe(A(()=>r.currentTime)),u=new I,l=.3;let p;h.subscribe(g=>{r.loop&&P(p)&&P(g)&&p>=r.duration-l&&g<=l&&u.next(p),p=g});const S=M(r,"enterpictureinpicture"),v=M(r,"leavepictureinpicture"),b=new m(Mr(r));S.subscribe(()=>b.next(!0)),v.subscribe(()=>b.next(!1));const w=new m(fs(r));return M(r,"fullscreenchange").pipe(A(()=>fs(r))).subscribe(w),{playing$:n,pause$:e("pause").pipe(K(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:M(r,"durationchange").pipe(A(()=>r.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:b,inFullscreen$:w}},qi=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let ds=!1,$t={};const Nr=r=>{ds=r},Fr=()=>{$t={}},Vr=r=>{r($t)},Di=(r,e)=>{ds&&($t.meta=$t.meta??{},$t.meta[r]=e)};class lt{name;constructor(e){this.name=e}next(e){if(!ds)return;$t.series=$t.series??{};const t=$t.series[this.name]??[];t.push([Date.now(),e]),$t.series[this.name]=t}}var Ft;(function(r){r.FitsContainer="FitsContainer",r.FitsThroughput="FitsThroughput",r.Buffer="Buffer",r.DroppedFramesLimit="DroppedFramesLimit",r.FitsQualityLimits="FitsQualityLimits"})(Ft||(Ft={}));const Ur=new lt("best_bitrate"),Hr=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class Us{last;history={};recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Yr='Assertion "ABR Tracks is empty array" failed',Gt=(r,{container:e,throughput:t,tuning:i,limits:s,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{hr(r,Yr);const l=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*i.containerSizeFactor,height:e.height*l*i.containerSizeFactor},S=p&&It(p),v=i.considerPlaybackRate&&P(o)?o:1,b=r.filter(T=>!Ht(T.quality)).sort((T,V)=>Kt(T.quality,V.quality)?-1:1),w=b.at(-1)?.quality,C=b.at(0)?.quality,g=Y(s)||P(s.min)&&P(s.max)&&Ri(s.max,s.min)||P(s.min)&&C&&Kt(s.min,C)||P(s.max)&&w&&Ri(s.max,w),E=v*Hr(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},q=b.filter(T=>(S?Ri(T.quality,S):!0)?(P(t)&&isFinite(t)&&P(T.bitrate)?t-a>=T.bitrate*E:!0)?i.lazyQualitySwitch&&P(i.minBufferToSwitchUp)&&c&&!Ht(c.quality)&&(n??0)<i.minBufferToSwitchUp&&Kt(T.quality,c.quality)?(x[T.quality]=Ft.Buffer,!1):!!h&&Ki(T.quality,h)?(x[T.quality]=Ft.DroppedFramesLimit,!1):g||(Y(s.max)||Ns(T.quality,s.max))&&(Y(s.min)||Ki(T.quality,s.min))?!0:(x[T.quality]=Ft.FitsQualityLimits,!1):(x[T.quality]=Ft.FitsThroughput,!1):(x[T.quality]=Ft.FitsContainer,!1))[0];q&&q.bitrate&&Ur.next(q.bitrate);const F=q??b[Math.ceil((b.length-1)/2)]??r[0];F.quality!==d?.last?.quality&&u({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${r.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -19,10 +19,10 @@ import{ValueSubject as g,Subject as I,Subscription as se,isNonNullable as P,Erro
|
|
|
19
19
|
playbackRate: ${o},
|
|
20
20
|
playbackRateFactor: ${v},
|
|
21
21
|
forwardBufferHealth: ${n},
|
|
22
|
-
bitrateFactor: ${
|
|
22
|
+
bitrateFactor: ${E},
|
|
23
23
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
24
24
|
droppedVideoMaxQualityLimit: ${h},
|
|
25
|
-
limitsAreInvalid: ${
|
|
25
|
+
limitsAreInvalid: ${g},
|
|
26
26
|
maxQualityLimit: ${s?.max},
|
|
27
27
|
minQualityLimit: ${s?.min},
|
|
28
28
|
|
|
@@ -34,13 +34,13 @@ import{ValueSubject as g,Subject as I,Subscription as se,isNonNullable as P,Erro
|
|
|
34
34
|
[selected track] ${F?.quality}
|
|
35
35
|
`});const G=F&&d&&d.history[F.id]&&ne()-d.history[F.id]<=i.trackCooldown&&(!d.last||F.id!==d.last.id);if(F?.id&&d&&!G&&d.recordSelection(F),G&&d?.last){const T=d.last;return d?.recordSwitch(T),u({message:`
|
|
36
36
|
[last selected] ${T?.quality}
|
|
37
|
-
`}),T}return d?.recordSwitch(F),F};var Ne=r=>new URL(r).hostname;const zr=300,Ti=(r,e=zr)=>new zi(t=>{const{width:i,height:s}=r.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const a=new ResizeObserver(br(n=>{const o=n[0];if(!o)return;let c,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,c=o.contentBoxSize[0].inlineSize):o.contentRect&&(c=o.contentRect.width,d=o.contentRect.height),P(c)&&P(d)&&t.next({width:c,height:d})},e));return a.observe(r),()=>a.disconnect()});class ki{onDroopedVideoFramesLimit$=new I;subscription=new se;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new I;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(M(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Yt(this.droppedFramesChecker.checkTime).pipe(K(()=>this.playing),K(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Qe(this.droppedFramesChecker.checkTime)),i=O(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Ht(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,s=t-this.prevDroppedVideoFrames,a=1-(i-s)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&Kt(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])=>Li(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 ci={};var X;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(X||(X={}));const Ee=(r,e)=>new zi(t=>{const i=s=>t.next(s);return r.on(e,i),()=>r.off(e,i)});class ps{subscription=new se;videoState=new de(X.DOWNLOADING_LIB);video;player;params;textTracksManager=new nt;droppedFramesManager=new ki;videoTracks$=new g([]);frameRatesByFrameHeight={};isLive$=new g(void 0);maxSeekBackTime$=new g(1/0);availableFrom$=new g(void 0);elementSize$=new g(void 0);liveOffset=new Ei;constructor(e){this.video=St(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:L.NETWORK,message:`Dash.js failed to load: ${s?.toString?.()}`,thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(ci.MediaPlayer=s.MediaPlayer,ci.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){w(ci.MediaPlayer,"dashjs not loaded"),w(ci.Debug,"dashjs not loaded"),this.player=ci.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?qi(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Ir(this.player),xr(this.player),this.params.tuning.requestQuick&&Rr(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,$)=>this.subscription.add(m.subscribe($,i));s(Ti(this.video),this.elementSize$),s(Ee(this.player,"error").pipe(A(m=>{const $=typeof m.error=="object"?m.error.code:m.error,x=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${$}`,message:x}})),e.error$),s(Ee(this.player,"playbackError").pipe(A(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=Ee(this.player,"qualityChangeRendered").pipe(K(({mediaType:m})=>m==="video"),A(({newQuality:m})=>this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===m)?.track));a.pipe(K(P)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(K(({to:m})=>m===X.STREAM_INITIALIZED),be()).subscribe(()=>{this.subscription.add(at(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===m)?.track},m=>{if(Y(m))return;const $=this.videoTracks$.getValue().find(({track:x})=>x.id===m.id)?.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a,onError:i}))},i)),this.subscription.add(at(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),s(Ee(this.player,"bufferStateChanged").pipe(K(({mediaType:m})=>m==="video"),A(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(Ee(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:$}})=>{const x=this.player.getDashMetrics(),H=x.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),q=x.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??yi.HTTP1,F={1:!0,0:!1}[H]??void 0;this.params.output.httpConnectionType$.next(q),this.params.output.httpConnectionReused$.next(F),e.hostname$.next(Ne($))}),s(Ee(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:$,availableFrom:x}}})=>{this.isLive$.next($),this.availableFrom$.next(x.getTime()),$||e.duration$.next(m);const H=[],q=this.player.getQualityFor("video");let F;for(const G of this.player.getBitrateInfoListFor("video")){const T=G.qualityIndex.toString(10),V=It(G),z=G.bitrate/1e3,te={width:G.width,height:G.height},ye=this.frameRatesByFrameHeight[G.height];if(V){const ke={id:T,quality:V,bitrate:z,size:te,fps:ye};H.push({track:ke,bitrateInfo:G}),G.qualityIndex===q&&(F=ke)}}this.videoTracks$.next(H),e.availableVideoTracks$.next(H.map(({track:G})=>G)),F&&e.currentVideoTrack$.next(F),this.videoState.setState(X.STREAM_INITIALIZED),this.videoState.startTransitionTo(X.READY)}),s(Ee(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const $=m.requestEndDate.getTime()-m.firstByteDate.getTime(),x=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(x,$)}),s(O(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),$=Gt(this.videoTracks$.getValue().map(({track:q})=>q),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),x=t.autoVideoTrackLimits.getTransition();x&&e.autoVideoTrackLimits$.next(x.to);const H=this.videoTracks$.getValue().find(({track:q})=>q===$);H?.bitrateInfo&&this.player.setQualityFor("video",H?.bitrateInfo.qualityIndex,!1)}),s(xe({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(K(P))}).pipe(K(({isLive:m})=>m),A(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=Ee(this.player,"playbackTimeUpdated").pipe(A(({time:m})=>m??0));s(xe({availableFrom:this.availableFrom$.pipe(K(P)),currentTime:n}),({availableFrom:m,currentTime:$})=>this.params.output.liveTime$.next(m+$*1e3)),s(n.pipe(K(()=>this.isLive$.getValue()===!1)),e.position$),s(Ee(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(Ee(this.player,"playbackEnded"),e.endedEvent$),s(Ee(this.player,"playbackProgress").pipe(A(()=>Vs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(Ee(this.player,"playbackPlaying"),()=>{this.videoState.setState(X.PLAYING),R(t.playbackState,f.PLAYING)}),s(Ee(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(Ee(this.player,"playbackPaused"),()=>{this.videoState.setState(X.PAUSED),R(t.playbackState,f.PAUSED)}),s(Ee(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===X.READY&&this.videoState.setState(X.READY)}),s(this.isLive$,e.isLive$),s(Ti(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=Lr(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(be()),e.firstBytesEvent$),s(Ee(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(xe({isLive:this.isLive$,isShort:e.duration$.pipe(A(m=>m<60))}),({isLive:m,isShort:$})=>{const x=!m&&$;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:x}}})}),s(n.pipe(K(m=>m>this.params.tuning.insufficientBufferRuleMargin),be()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Ee(this.player,"manifestLoaded").pipe(be()).subscribe(()=>{this.subscription.add(Ee(this.player,"playbackPlaying").pipe(be(),Zt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(Ee(this.player,"manifestLoaded"),m=>{if(m.data?.Period?.AdaptationSet){const $=[];for(const x of m.data?.Period?.AdaptationSet)if(x.contentType==="text"){const H=x.Representation?.id,q=new URL(x.Representation?.BaseURL,m.data?.baseUri).toString(),F="internal",G=x.lang;$.push({id:H,url:q,type:F,language:G})}t.internalTextTracks.startTransitionTo($)}}),this.subscription.add(Ct(this.video,t.isLooped,i));const{volumeState$:l,looped$:p,playbackRateState$:S,inPiP$:v,inFullscreen$:b,pause$:D,playing$:C}=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:C,pause$:D,tracks$:this.videoTracks$.pipe(A(m=>m.map(({track:$})=>$)))}),this.subscription.add(gt(this.video,t.volume,l,i)),this.subscription.add(l.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(wt(this.video,t.playbackRate,S,i)),this.subscription.add(v.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(X.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(X.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=Me(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,fe.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(X.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(X.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===X.DOWNLOADING_LIB||e===X.STREAM_INITIALIZED))switch(i?.to!==f.PAUSED&&s.state===j.Requested&&e!==X.STOPPED&&t!==f.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case f.STOPPED:{switch(e){case X.STOPPED:break;case X.PLAYING:case X.PAUSED:case X.READY:this.stop();break;default:N(e)}break}case f.READY:{switch(e){case X.STOPPED:this.prepare();break;case X.PLAYING:case X.PAUSED:case X.READY:break;default:N(e)}break}case f.PLAYING:{switch(e){case X.PLAYING:break;case X.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case X.READY:this.play();break;case X.STOPPED:this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case X.PLAYING:this.pause(),this.liveOffset.pause();break;case X.PAUSED:break;case X.READY:this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case X.STOPPED:this.prepare();break;default:N(e)}break}default:N(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}bt(this.video),this.params.output.element$.next(void 0)}}var ai=r=>{switch(r){case"mobile":return je.Q_144P;case"lowest":return je.Q_240P;case"low":return je.Q_360P;case"sd":case"medium":return je.Q_480P;case"hd":case"high":return je.Q_720P;case"fullhd":case"full":return je.Q_1080P;case"quadhd":case"quad":return je.Q_1440P;case"ultrahd":case"ultra":return je.Q_2160P}};const ms=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Dt=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!ms(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return ms(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function _e(){return ne()}function Hs(r){return _e()-r}function gs(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,c=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return c&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function qr(r,e,t){const i=(...s)=>{t.apply(null,s),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ri(r,e,t,i){const s=window.XMLHttpRequest;let a,n,o,c=!1,d=0,h,u,l=!1,p="arraybuffer",S=7e3,v=2e3,b=()=>{if(c)return;w(h);const z=Hs(h);let te;if(z<v){te=v-z,setTimeout(b,te);return}v*=2,v>S&&(v=S),n&&n.abort(),n=new s,H()};const D=z=>(a=z,V),C=z=>(u=z,V),m=()=>(p="json",V),$=()=>{if(!c){if(--d>=0){b(),i&&i();return}c=!0,u&&u(),t&&t()}},x=z=>(l=z,V),H=()=>{h=_e(),n=new s,n.open("get",r);let z=0,te,ye=0;const ke=()=>(w(h),Math.max(h,Math.max(te||0,ye||0)));if(a&&n.addEventListener("progress",U=>{const re=_e();a.updateChunk&&U.loaded>z&&(a.updateChunk(ke(),U.loaded-z),z=U.loaded,te=re)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(c)return;w(n);const U=n.status;if(U>=200&&U<300){if(n.response.byteLength&&a){const re=n.response.byteLength-z;re&&a.updateChunk&&a.updateChunk(ke(),re)}u&&u(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),l){const U=()=>{w(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=_e(),n.removeEventListener("readystatechange",U))};n.addEventListener("readystatechange",U)}return n.responseType=p,n.send(),V},V={withBitrateReporting:D,withParallel:x,withJSONResponse:m,withRetryCount:z=>(d=z,V),withRetryInterval:(z,te)=>(P(z)&&(v=z),P(te)&&(S=te),V),withTimeout:z=>(o=z,V),withFinally:C,send:H,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return V}const Wr=100,Qr=2e3,jr=500;let Jr=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-jr;if(t-e>Qr){let i=0,s=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,s+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const c=a.bytes*n/o;s+=c,a.start=t,a.bytes-=c}}}if(s>0&&i>0){const a=s*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>Wr&&(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 Xr{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=_e(),s=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=c=>{e._complete=1,e._responseData=c,e._downloadTime=_e()-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=Ri(t,a,()=>s("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=_e()}_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=_e();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,s){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Di=1e4,Pi=3,Kr=300,Zr=2e3,ea=6e4,ta=10,ia=1,sa=500;class ra{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 Jr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=gs(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=gs(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||P(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{qr(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Xr(Pi,Di,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let a=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const $=a&&(!h||h===this.rep);return $||t("Not running!"),$},l=($,x,H)=>{c&&c.abort(),c=Ri(this.urlResolver.resolve($,!1),x,H,()=>this._retryCallback()).withTimeout(Di).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Pi).withFinally(()=>{c=null}).send()},p=($,x,H)=>{w(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),x,H,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=$=>{const x=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${x}=>${$}`),i.playbackRate=$)},v=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const H=_e()-1e4;let q=0;for(let G=0;G<this.bufferStates.length;G++){const T=this.bufferStates[G];$=Math.min($,T.buf),T.ts<H&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${$} drop=${q} jitter=${this.sourceJitter}`);let F=$-ia;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?S(1.15):F>1?S(1.1):F>.3?S(1.05):S(1)}},D=$=>{let x;const H=()=>x&&x.start?x.start.length:0,q=U=>x.start[U]/1e3,F=U=>x.dur[U]/1e3,G=U=>x.fragIndex+U,T=(U,re)=>({chunkIdx:G(U),startTS:q(U),dur:F(U),discontinuity:re}),V=()=>{let U=0;if(x&&x.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,pe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,$e=re;this.sourceJitter>1&&($e+=this.sourceJitter-1);let Ce=x.dur.length-1;for(;Ce>=0&&($e-=x.dur[Ce],!($e<=0));--Ce);U=Math.min(Ce,x.dur.length-1-pe),U=Math.max(U,0)}return T(U,!0)},z=U=>{const re=H();if(!(re<=0)){if(P(U)){for(let pe=0;pe<re;pe++)if(q(pe)>U)return T(pe)}return V()}},te=U=>{const re=H(),pe=U?U.chunkIdx+1:0,$e=pe-x.fragIndex;if(!(re<=0)){if(!U||$e<0||$e-re>ta)return t(`Resync: offset=${$e} bChunks=${re} chunk=`+JSON.stringify(U)),V();if(!($e>=re))return T(pe-x.fragIndex,!1)}},ye=(U,re,pe)=>{d&&d.abort(),d=Ri(this.urlResolver.resolve(U,!0,this.lowLatency),re,pe,()=>this._retryCallback()).withTimeout(Di).withRetryCount(Pi).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(U,re)=>{ye($,pe=>{if(!u())return;x=pe;const $e=!!x.lowLatency;$e!==this.lowLatency&&v($e);let Ce=0;for(let ot=0;ot<x.dur.length;++ot)Ce+=x.dur[ot];Ce>0&&(w(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ce/x.dur.length)),s({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,U(z(re))},()=>this._handleNetworkError())},nextChunk:te}},C=()=>{a=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),w(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:$=>{const{videoElement:x,logger:H}=this.params;let q=D(e.jidxUrl),F,G,T,V,z=0,te,ye,ke;const U=()=>{te&&(clearTimeout(te),te=void 0);const ae=Math.max(sa,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=z+ae,Fe=_e(),De=Math.min(1e4,we-Fe);z=Fe;const vt=()=>{d||u()&&q.seek(()=>{u()&&(z=_e(),re(),U())})};De>0?te=window.setTimeout(()=>{this.paused?U():vt()},De):vt()},re=()=>{let ae;for(;ae=q.nextChunk(V);)V=ae,oi(ae);const we=q.nextChunk(T);if(we){if(T&&we.discontinuity){H("Detected discontinuity; restarting playback"),this.paused?U():(C(),this._initPlayerWith(e));return}ot(we)}else U()},pe=(ae,we)=>{if(!u()||!this.sourceBuffer)return;let Fe,De,vt;const Te=Ye=>{window.setTimeout(()=>{u()&&pe(ae,we)},Ye)};if(this.sourceBuffer.updating)H("Source buffer is updating; delaying appendBuffer"),Te(100);else{const Ye=_e(),Ae=x.currentTime;!this.paused&&x.buffered.length>1&&ye===Ae&&Ye-ke>500&&(H("Stall suspected; trying to fix"),this._fixupStall()),ye!==Ae&&(ye=Ae,ke=Ye);const Pe=this._getBufferSizeSec();if(Pe>30)H(`Buffered ${Pe} seconds; delaying appendBuffer`),Te(2e3);else try{this.sourceBuffer.appendBuffer(ae),this.videoPlayStarted?(this.bufferStates.push({ts:Ye,buf:Pe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(dt){if(dt.name==="QuotaExceededError")H("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&(Fe=this.sourceBuffer.buffered.start(0),De=Ae,De-Fe>4&&this.sourceBuffer.remove(Fe,De-3)),Te(1e3);else throw dt}}},$e=()=>{G&&F&&(H([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(T)]),pe(G,function(){G=null,re()}))},Ce=ae=>e.fragUrlTemplate.replace("%%id%%",ae.chunkIdx),ot=ae=>{u()&&p(Ce(ae),(we,Fe)=>{if(u()){if(Fe/=1e3,G=we,T=ae,n=ae.startTS,Fe){const De=Math.min(10,ae.dur/Fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}$e()}},()=>this._handleNetworkError())},oi=ae=>{u()&&(w(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ce(ae),!1)))},zt=ae=>{u()&&(e.cachedHeader=ae,pe(ae,()=>{F=!0,$e()}))};a=!0,q.seek(ae=>{if(u()){if(z=_e(),!ae){U();return}V=ae,!Y($)||ae.startTS>$?ot(ae):(T=ae,re())}},$),e.cachedHeader?zt(e.cachedHeader):l(e.headerUrl,zt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),P(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,w(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return P(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let l,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(p=this._getBufferSizeSec(),S=u/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}l=this._selectQuality(u),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${u}`)},a=(()=>({updateChunk:(l,p)=>{const S=_e();if(this.chunkRateEstimator.addInterval(l,S,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-l,speed:b}),!0}},get:()=>{const l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=a.get();if(u&&o&&this.autoQuality){if(c&&u>o&&Hs(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,l)=>{const p=a.updateChunk(u,l);return p&&d(),p},notifySwitch:u=>{const l=_e();u<o&&(n=l),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=Ri(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Di).withRetryCount(Pi).withRetryInterval(Kr,Zr).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Dt(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,a=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&s.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=d,o.push(c))}),o.sort(function(c,d){return c.video&&d.video?d.video.height-c.video.height:d.bitrate-c.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ea))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var J;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(J||(J={}));const aa=[J.PAUSED,J.PLAYING,J.READY],na=[J.PAUSED,J.PLAYING,J.READY];class oa{subscription=new se;video;videoState=new de(J.STOPPED);dash;representations$=new g([]);textTracksManager=new nt;droppedFramesManager=new ki;maxSeekBackTime$=new g(1/0);zeroTime$=new g(void 0);liveOffset=new Ei;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:L.WTF,message:"DashLiveProvider internal logic error",thrown:s})};O(this.videoState.stateChangeStarted$.pipe(A(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(s)}`})}),this.video=St(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(A(s=>s.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(J.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(le(),A(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(xe({zeroTime:this.zeroTime$.pipe(K(P)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:a})=>this.params.output.liveTime$.next(s+a*1e3),t)).add(Ct(this.video,this.params.desiredState.isLooped,t)).add(gt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(wt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const a=s&&lr(s);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case J.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(f.STOPPED);break;case J.MANIFEST_READY:case J.READY:this.params.desiredState.playbackState.getTransition()?.to===f.READY&&this.params.desiredState.playbackState.setState(f.READY);break;case J.PAUSED:this.params.desiredState.playbackState.setState(f.PAUSED);break;case J.PLAYING:this.params.desiredState.playbackState.setState(f.PLAYING);break;default:return N(s.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Oe(["init"])).pipe(Qe(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}createLiveDashPlayer(){const e=new ra({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&P(t)?t:Gt(e.map(({track:d})=>d),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=s?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(n||a!==o)&&this.setVideoTrack(s),c&&this.setAutoQuality(i),n||c||a!==o){const d=e.find(({track:h})=>h.id===a)?.representation;w(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;w(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===f.PAUSED&&i===J.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Me(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:L.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const a=s.name??s.index.toString(10),n=ai(s.name)??It(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:a,quality:n,bitrate:o,size:c};i.push({track:d,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===J.MANIFEST_READY&&this.videoState.setState(J.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),P(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(J.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(na.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==f.PAUSED&&a.state===j.Requested&&aa.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_READY),this.dash.attachSource(Me(this.params.source.url));return;case J.MANIFEST_READY:this.videoState.startTransitionTo(J.READY),this.prepare();break;case J.READY:if(i===f.PAUSED)this.videoState.setState(J.PAUSED);else if(i===f.PLAYING){this.videoState.startTransitionTo(J.PLAYING);const c=s?.from;c&&c===f.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(J.PAUSED)})}return;case J.PLAYING:i===f.PAUSED&&(this.videoState.startTransitionTo(J.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case J.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(J.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(J.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Me(this.params.source.url,c))}return;default:return N(e)}}}var cs=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?yi.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},He=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){const s=r.start(i)*1e3,a=r.end(i)*1e3;s<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const da=r=>{const e=document.createElement("a");return e.href=r,e.origin},ca=r=>{const e=document.createElement("a");return e.href=r,e.host};class Ys{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,a,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(this._xhr){if(this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(i=>i.split(":").map(s=>s.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(ca(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 Bi{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let a=0;for(let n=0,o=s.length;n<o;n++)a+=s.end(n)-s.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,a,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,l=0;const p=v=>{s(Bi._str2ua(v.substr(c))),c=v.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=Rt(S)),this._lastXhr=new Ys(S,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const b=Date.now()-d;this._params.onBandwidthChange({size:v.length,duration:b,speed:8*v.length/(b/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),a?.()},v=>{if(v.length-c>o&&p(v),u===0){u=Date.now();return}l=v.length-h;const b=Date.now()-u;l>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:l,duration:b,speed:8*l/(b/1e3)}),l=0,h=v.length,u=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},n,(v,b,D)=>this._params.onError(v,b,D))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Bi._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 ua{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},s=t.exec(e),a=s?.[1]==="-"?-1:1,n={years:i(s?.[2],a),months:i(s?.[3],a),weeks:i(s?.[4],a),days:i(s?.[5],a),hours:i(s?.[6],a),minutes:i(s?.[7],a),seconds:i(s?.[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Rt(i)),new Ys(i,t,s=>{this.attachManifest(s,t,da(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,a,n)=>this._params.onError(s,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,h)=>{const u=d.attributes.getNamedItem(h);return u?u.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),l=h&&h.getElementsByTagName("Initialization")[0],p=l&&n(l,"range").split("-");if(!p||!u){const m=d.parentElement;if(m?.getAttribute("contentType")==="text"){const $=d.getAttribute("id")??void 0,x=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,H=m.getAttribute("lang")??void 0;x&&c.push({id:$,url:x,language:H})}return}const S=.1,v=Number(d.attributes.getNamedItem("bandwidth")?.value),b=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let D;const C=d.attributes.getNamedItem("frameRate")?.value??void 0;D=C?qi(C):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:v,baseURL:b,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:D,bufferSize:S*v/8,bufferLength:S,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:h,url:u})=>{const l=document.createElement("track");u&&l.setAttribute("src",u),d&&l.setAttribute("id",d),h&&l.setAttribute("srclang",h),this._video.appendChild(l)}),this._representations.sort((d,h)=>h.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:c})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let a=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,a);const n=new DataView(s.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let c=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const h=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let l=0;l<h;l+=1){const p=d+(n.getUint32(a,!1)&2147483647),S=c+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:c/o,toTime:S/o,fromOffset:d,toOffset:p-1}),d=p,c=S}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let s,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const h=this._appendVector[String(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}u=p.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},u*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},c=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Bi({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",c),i.removeEventListener("webkitsourceopen",c)};i.addEventListener("sourceopen",c,!1),i.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(s.toTime<i.to+a){const n=this._findRef(s.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,n.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||Y(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let i;for(let s=0;s<t.length;s++){const a=t[s];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!i||a.fromTime<i.fromTime)&&(i=a)}if(!i){const s=t[t.length-1];if(e>s.toTime)return s}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>i&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Z;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Z||(Z={}));const ha=[Z.PAUSED,Z.PLAYING];class la{videoState=new de(Z.STOPPED);subscription=new se;video;buffer;dash;representations$=new g([]);currentRepresentation$=new g(void 0);params;textTracksManager=new nt;droppedFramesManager=new ki;elementSize$=new g(void 0);dashLiteEvents={idxRequestPing$:new I,responseHeaders$:new I,manifestReady$:new I,representationPlay$:new I,error$:new I};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),O(this.videoState.stateChangeStarted$.pipe(A(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Nr(this.video),this.dash=new ua({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:s,category:L.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:L.WTF,message:"DashProvider internal logic error",thrown:o})},s=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},a=yt(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{Y(this.params.desiredState.seekState.getState().state!==j.Applying)&&(this.videoState.getState()===Z.PLAYING||this.videoState.getState()===Z.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(wt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(A(o=>o.map(({track:c})=>c)))}),n(Ti(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Z.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(A(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(O(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).pipe(A(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState()?.id,u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),p=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let S;if(!p&&P(h))S=h;else{const v=He(this.video.buffered,this.video.currentTime*1e3),b=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,D=Math.min(v/b,1);S=Gt(c.map(({track:m})=>m),{container:l,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:D,playbackRate:this.video.playbackRate,current:c.find(({representation:m})=>m===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const C=t.autoVideoTrackLimits.getTransition();C&&e.autoVideoTrackLimits$.next(C.to)}return P(S)?c.find(({track:v})=>v.id===S)?.representation:void 0}),le()).subscribe(this.currentRepresentation$,i)).add(xe({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(K(o=>o.to===Z.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(K(P))}).pipe(be()).subscribe(()=>this.videoState.setState(Z.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(K(P),le((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=He(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!s())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ne(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=cs(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(be(),Zt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(K(P)).subscribe(this.handleRepresentationPlay,i)).add(O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return N(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const a=s.name??s.id??s.height.toString(10),n=(s.name&&ai(s.name))??It(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:a,quality:n,bitrate:o,size:c,fps:d};i.push({track:h,representation:s})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),t?.length>0){const s=[];for(const a of t){const n=a.id||`${a.language}_${Date.now()}`;s.push({id:n,type:"internal",url:a.url||"",language:a.language,isAuto:a.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(Z.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return w(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(!t)switch(s?.to!==f.PAUSED&&a.state===j.Requested&&ha.includes(e)&&this.seek(a.position,a.forcePrecise),e){case Z.STOPPED:this.videoState.startTransitionTo(Z.MANIFEST_LOADED),this.prepare();return;case Z.MANIFEST_LOADED:this.videoState.startTransitionTo(Z.INITIAL_REPRESENTATION_SELECTED);return;case Z.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Z.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Z.METADATA_LOADED:this.videoState.startTransitionTo(Z.READY),this.dash.updateRefsForCurrentTime();return;case Z.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Z.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}var Re;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Re||(Re={}));var _i;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(_i||(_i={}));var Ke;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Ke||(Ke={}));var ee;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(ee||(ee={}));var ei;(function(r){r.MP4="mp4",r.WEBM="webm"})(ei||(ei={}));var Mi;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Mi||(Mi={}));var me;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(me||(me={}));var ti=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const fa=16;let Gs=!1;try{Gs=Gi().browser===ns.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=fa}catch(r){console.error(r)}let pa=class{bufferFull$=new I;error$=new I;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;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:N(t)}}};var Oi=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};let Tt=class{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}},zs=class extends Tt{},ma=class extends Tt{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}},ga=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},Sa=class extends Tt{data;constructor(e){super(e),this.data=this.content}},$i=class extends Tt{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},ba=class extends $i{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}},ya=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},Ta=class extends Tt{parseChildrenBoxes(){return ni(this.content)}};var Vt;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Vt||(Vt={}));let va=class extends $i{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Vt.MONOSCOPIC;break;case 1:this.stereoMode=Vt.TOP_BOTTOM;break;case 2:this.stereoMode=Vt.LEFT_RIGHT;break;case 3:this.stereoMode=Vt.STEREO_CUSTOM;break;case 4:this.stereoMode=Vt.RIGHT_LEFT;break}this.cursor+=1}},Ea=class extends $i{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},ka=class extends $i{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},$a=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},Aa=class extends $i{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()}},wa=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},Da=class extends Tt{parseChildrenBoxes(){return ni(this.content)}};const Pa={ftyp:ma,moov:ga,mdat:Sa,sidx:ba,trak:ya,mdia:$a,tkhd:Aa,minf:wa,sv3d:Ta,st3d:va,prhd:Ea,proj:Da,equi:ka,unknown:zs};let xa=class{createBox(e,t){const i=Pa[e];return i?new i(t):new zs(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Wi.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Wi=new xa;function pi(r,e){const t=new TextDecoder("ascii");let i=r.byteOffset,s=[];for(;i<r.byteLength;){const a=t.decode(new DataView(r.buffer,i,1));if(a===e[s.length]?s.push(a):s=[],s.length===4&&s.join("")===e){const o=new DataView(r.buffer,i-7,4).getUint32(0);return i-7+o>r.byteLength?null:Wi.createBox(e,new DataView(r.buffer,i-7))}i++}return null}function La(r,e){const t=[];let i=0;for(;i<r.byteLength;){const s=pi(new DataView(r.buffer,r.byteOffset+i,r.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function ni(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Wi.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Ra=new TextDecoder("ascii"),Ia=r=>Ra.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Ca=r=>{const e=Wi.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:ee.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Ba=r=>{const e=La(r,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(r.buffer,r.byteOffset,t)}return null},_a=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Mi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(pi(r,"sv3d")){e.is3dVideo=!0;const i=pi(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=pi(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=pi(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Ma={validateData:Ia,parseInit:_a,getIndexRange:()=>{},parseSegments:Ca,parseFeedableSegmentChunk:Ba};var E;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(E||(E={}));var B;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(B||(B={}));const Ss={[E.EBML]:{type:B.Master},[E.EBMLVersion]:{type:B.UnsignedInteger},[E.EBMLReadVersion]:{type:B.UnsignedInteger},[E.EBMLMaxIDLength]:{type:B.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:B.UnsignedInteger},[E.DocType]:{type:B.String},[E.DocTypeVersion]:{type:B.UnsignedInteger},[E.DocTypeReadVersion]:{type:B.UnsignedInteger},[E.Void]:{type:B.Binary},[E.Segment]:{type:B.Master},[E.SeekHead]:{type:B.Master},[E.Seek]:{type:B.Master},[E.SeekID]:{type:B.Binary},[E.SeekPosition]:{type:B.UnsignedInteger},[E.Info]:{type:B.Master},[E.TimestampScale]:{type:B.UnsignedInteger},[E.Duration]:{type:B.Float},[E.Tracks]:{type:B.Master},[E.TrackEntry]:{type:B.Master},[E.Video]:{type:B.Master},[E.Projection]:{type:B.Master},[E.ProjectionType]:{type:B.UnsignedInteger},[E.ProjectionPrivate]:{type:B.Master},[E.Chapters]:{type:B.Master},[E.Cluster]:{type:B.Master},[E.Timestamp]:{type:B.UnsignedInteger},[E.SilentTracks]:{type:B.Master},[E.SilentTrackNumber]:{type:B.UnsignedInteger},[E.Position]:{type:B.UnsignedInteger},[E.PrevSize]:{type:B.UnsignedInteger},[E.SimpleBlock]:{type:B.Binary},[E.BlockGroup]:{type:B.Master},[E.EncryptedBlock]:{type:B.Binary},[E.Attachments]:{type:B.Master},[E.Tags]:{type:B.Master},[E.Cues]:{type:B.Master},[E.CuePoint]:{type:B.Master},[E.CueTime]:{type:B.UnsignedInteger},[E.CueTrackPositions]:{type:B.Master},[E.CueTrack]:{type:B.UnsignedInteger},[E.CueClusterPosition]:{type:B.UnsignedInteger},[E.CueRelativePosition]:{type:B.UnsignedInteger},[E.CueDuration]:{type:B.UnsignedInteger},[E.CueBlockNumber]:{type:B.UnsignedInteger},[E.CueCodecState]:{type:B.UnsignedInteger},[E.CueReference]:{type:B.Master},[E.CueRefTime]:{type:B.UnsignedInteger}},qs=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ni(r,t),s=i in Ss,a=s?Ss[i].type:B.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Ni(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Ni=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ft=(r,e)=>{switch(e){case B.SignedInteger:return r.getInt8(0);case B.UnsignedInteger:return Ni(r);case B.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case B.String:return new TextDecoder("ascii").decode(r);case B.UTF8:return new TextDecoder("utf-8").decode(r);case B.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case B.Master:return r;case B.Binary:return r;default:N(e)}},ii=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=qs(i);if(!e(s))return;s.type===B.Master&&ii(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},Oa=r=>{if(r.getUint32(0)!==E.EBML)return!1;let e,t,i;const s=qs(r);return ii(s.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=ft(o,n):a===E.DocType?t=ft(o,n):a===E.DocTypeReadVersion&&(i=ft(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ws=[E.Info,E.SeekHead,E.Tracks,E.TrackEntry,E.Video,E.Projection,E.ProjectionType,E.ProjectionPrivate,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],Na=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],Fa=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ii(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===E.SeekID){const b=ft(S,p);d=Ni(b)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?i=ft(S,p):l===E.Duration?s=ft(S,p):l===E.SeekPosition&&d===E.Cues?c=ft(S,p):l===E.Tracks?ii(S,({tag:b,type:D,value:C})=>b===E.ProjectionType?(h=ft(C,D)===1,!1):!0):a&&n&&Ws.includes(l)&&(o=!0),!o}),w(e,"Failed to parse webm Segment start"),w(t,"Failed to parse webm Segment end"),w(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:u,projectionType:Mi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Va=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ua=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ii(r,({tag:o,type:c,value:d})=>{switch(o){case E.Cues:t=!0;break;case E.CuePoint:n&&s(n)&&a.push(n),n={};break;case E.CueTime:n&&(n.time=ft(d,c));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=ft(d,c));break;default:t&&Ws.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:ee.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Ha=r=>{let e=0,t=!1;try{ii(r,i=>i.tag===E.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Na.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Ya={validateData:Oa,parseInit:Fa,getIndexRange:Va,parseSegments:Ua,parseFeedableSegmentChunk:Ha},Qs=1e4,Ga=3e4,za=5e3,qa=Qs,Wa=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?ai(a):void 0)??It({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},Qa=({id:r,bitrate:e})=>({id:r,bitrate:e}),ja=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},Ja=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),xi=r=>{const e=[];let t=0,i=r.length-1;for(;t<Qs&&i>=0;)e.unshift(r[i]),t+=r[i].time.to-r[i].time.from,i--;return e};let bs=class{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);playingRepresentationInit$=new g(void 0);error$=new I;gaps=[];isSeekingLive=!1;subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new AbortController;destroyAbortController=new AbortController;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,s,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1,manifest:d}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!d?.dynamic,this.container=i,i){case ei.MP4:this.containerParser=Ma;break;case ei.WEBM:this.containerParser=Ya;break;default:N(i)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);w(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new pa(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);w(i,"No init buffer for starting representation"),w(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);w(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),w(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();P(a)&&(this.searchGaps(i,t),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(w(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=He(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Oi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=He(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===ee.FED&&!o.length&&He(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;for(const s of e)s.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from}),i=s.time.to;P(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d)return;const h=xi(d.segmentReference.segments);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);w(i);const s=xi(i.segmentReference.segments),a=this.initData.get(i.id);if(w(a,"No init buffer for starting representation"),w(s,"No segments for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t)return;const i=t.segmentReference.segments.map(o=>({...o,status:ee.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.round(a)>=Math.round(o.time.from)&&Math.round(a)<=Math.round(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=xi(i);this.segments.set(t.id,[...o])}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,D=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+D||p<=i+D;return(u===ee.NONE||u===ee.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!ti(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==Ke.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===ee.NONE||l.status===ee.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ke.BYTE_RANGE:{s=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Ke.TEMPLATE:{const d=e.at(0);s=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:N(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await oe(c,async function*(){const d=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(s,{range:a,onProgress:(d,h)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,h,c)}catch(u){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:c,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(d)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&P(i)&&(t=He(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,s,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=u=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),u.segment.status=ee.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const l of this.representations.values())if(l.id!==t)for(const p of this.segments.get(l.id)??[])p.status===ee.FED&&p.time.from===u.segment.time.from&&p.time.to===u.segment.time.to&&(p.status=ee.NONE);this.activeSegments.delete(u),this.detectGapsWhenIdle(t,[u.segment])},c=this.representations.get(t);if(!c)return;const d=c.segmentReference.type,h=e.byteLength;for(const u of this.activeSegments){const{segment:l}=u,p=d===Ke.BYTE_RANGE,S=p?l.byte.to-l.byte.from+1:h;if(u.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const b=p?l.byte.from-i:0,D=p?l.byte.to-i:e.byteLength,C=b<s,m=D<=s;if(l.status===ee.DOWNLOADING&&C&&m){l.status=ee.DOWNLOADED,this.activeSegments.delete(u);const $=new DataView(e.buffer,e.byteOffset+b,S);this.sourceBufferTaskQueue.append($,a).then(x=>x&&!a.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&C&&(u.loadedBytes=Math.min(S,s-b),u.loadedBytes>u.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+b+u.feedingBytes,u.loadedBytes-u.feedingBytes),x=u.loadedBytes===S?$:this.containerParser.parseFeedableSegmentChunk($);x?.byteLength&&(l.status=ee.PARTIALLY_FED,u.feedingBytes+=x.byteLength,this.sourceBufferTaskQueue.append(x,a).then(H=>{if(a.aborted)n();else if(H)u.fedBytes+=x.byteLength,u.fedBytes===S&&o(u);else{if(u.feedingBytes<S)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=gi(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?xi(h):h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h="size"in d?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===ee.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===ee.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===ee.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===ee.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=ee.PARTIALLY_EJECTED:s.status=ee.NONE)}}};var Jt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Jt||(Jt={}));let Xa=class{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new AbortController;subscription=new se;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Rt(t));const i=yield fetch(t,{signal:this.abortAllController.signal}).catch(ui);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Jt.HEADER:Jt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(i)switch(t){case Jt.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case Jt.PARAM:{const T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:N(t)}this.requestQuic&&(c=Rt(c));let h=this.abortAllController.signal,u;if(n){const T=new AbortController;if(u=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{T.abort()}catch(V){ui(V)}}),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(V){ui(V)}h=T.signal}const l=ne(),p=yield fetch(c,{priority:a,headers:d,signal:h}).catch(ui),S=ne();if(this.throughputEstimator?.addRawRtt(S-l),!p)return u?.unsubscribe(),null;if(!p.ok||!p.body)return u?.unsubscribe(),Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const v=parseInt(p.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!v){const T=yield p.arrayBuffer();return this.throughputEstimator?.addRawSpeed(T.byteLength,ne()-S),s?.(new DataView(T),T.byteLength),u?.unsubscribe(),T}if(!s&&!o)return u?.unsubscribe(),p.arrayBuffer();const[b,D]=p.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(D);let m=0;const $=new ArrayBuffer(v),x=new Uint8Array($),H=new DataView($);let q=!1;const F=T=>{u?.unsubscribe(),q=!0,ui(T)},G=oe(h,async function*({done:T,value:V}){if(m===0&&this.lastRequestFirstBytes$.next(ne()-l),h.aborted){u?.unsubscribe();return}!T&&V&&(x.set(V,m),m+=V.byteLength,s?.(H,m),yield C?.read().then(G,F))}.bind(this));return yield C?.read().then(G,F),u?.unsubscribe(),q?null:$}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ke.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ke.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ke.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const D=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!D)return null;v=new DataView(D)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==Ke.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(n=>({...n,status:ee.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))};const ui=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},ys=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ji=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},Ka=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=ys(l);else if(p){const m=ys(p);P(m)&&(u=m)}else v&&(u=parseInt(v,10));let b=0;const D=a.getAttribute("profiles")?.split(",")??[],C=D.includes(_i.WEBM_AS_IN_FFMPEG)||D.includes(_i.WEBM_AS_IN_SPEC)?ei.WEBM:ei.MP4;for(const m of o){const $=m.getAttribute("mimeType"),x=m.getAttribute("codecs"),H=m.getAttribute("contentType")??$?.split("/")[0],q=m.getAttribute("profiles")?.split(",")??[],F=m.querySelectorAll("Representation"),G=m.querySelector("SegmentTemplate");if(H===Re.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=m.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Re.TEXT].push({id:V,lang:z,isAuto:ke,kind:Re.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??$,z=T.getAttribute("codecs")??x??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=m.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,Ce=pe?qi(pe):void 0,ot=T.getAttribute("id")??(b++).toString(10),oi=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,zt=`${ot}@${oi}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Fe=[...D,...q,...ye];let De;const vt=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(vt){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,dt]=Ae.split("-").map(Ge=>parseInt(Ge,10)),Ve={from:Pe,to:dt},tt=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[_t,Et]=tt?tt.split("-").map(Ge=>parseInt(Ge,10)):[],it=tt?{from:_t,to:Et}:void 0;De={type:Ke.BYTE_RANGE,url:we,initRange:Ve,indexRange:it}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),dt=Te.getAttribute("initialization")??"",Ve=Te.getAttribute("media"),tt=parseInt(Te.getAttribute("startNumber")??"",10)??1,_t=Ji(dt,Ae);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");const Et=Te.querySelectorAll("SegmentTimeline S")??[],it=[];let Ge=0;if(Et.length){let Mt=tt,ze=0;for(const Ot of Et){const qe=parseInt(Ot.getAttribute("d")??"",10),ve=parseInt(Ot.getAttribute("r")??"",10)||0,st=parseInt(Ot.getAttribute("t")??"",10);ze=Number.isFinite(st)?st:ze;const Ue=qe/Pe*1e3,ct=ze/Pe*1e3;for(let kt=0;kt<ve+1;kt++){const di=Ji(Ve,{...Ae,segmentNumber:Mt.toString(10),segmentTime:(ze+kt*qe).toString(10)}),Ai=(ct||0)+kt*Ue,qt=Ai+Ue;Mt++,it.push({time:{from:Ai,to:qt},url:di})}ze+=(ve+1)*qe,Ge+=(ve+1)*Ue}}else if(P(u)){const ze=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,Ot=Math.ceil(u/ze);let qe=0;for(let ve=1;ve<Ot;ve++){const st=Ji(Ve,{...Ae,segmentNumber:ve.toString(10),segmentTime:qe.toString(10)});it.push({time:{from:qe,to:qe+ze},url:st}),qe+=ze}}De={type:Ke.TEMPLATE,baseUrl:we,initUrl:_t,totalSegmentsDurationMs:Ge,segments:it}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ye={video:Re.VIDEO,audio:Re.AUDIO,text:Re.TEXT}[te];Ye&&s[Ye].push({id:zt,kind:Ye,segmentReference:De,profiles:Fe,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:Ce,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},ts=1e3,Ts=["timeupdate","progress","play","seeked","stalled","waiting"];var Je;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Je||(Je={}));let Za=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Je.NONE);currentVideoRepresentation$=new g(void 0);currentVideoRepresentationInit$=new g(void 0);error$=new I;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);isLive$=new g(!1);liveDuration$=new g(0);liveAvailabilityStartTime$=new g(void 0);bufferLength$=new g(0);liveLoadBufferLength$=new g(0);forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Xa({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Me(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Je.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Je.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=Ka(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Re.TEXT);return this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){w(this.element),this.manifestUrlString=Me(this.manifestUrlString,e,fe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=oe(this.destroyController.signal,async function*(e,t){w(this.manifest),w(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Je.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new bs(Re.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new bs(Re.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Yt(ts).subscribe(n=>{if(this.element?.paused){const o=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Me(this.manifestUrlString,o+1e3,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...Ts.map(n=>M(this.element,n))).pipe(fr(ts),A(n=>this.element?He(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async o=>{w(this.element);const c=this.element.playbackRate,d=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),h=Ga*c,u=qa*c,l=za*c;n=o>n?o:n;const p=d===0&&o<l,S=d!==0&&o<h+l&&o>=h,v=d!==0&&o<h;if(v||S){const b=n-(h+u),D=Math.trunc(d+b/c);let C;o?D>0?C=D:C=0:C=d,this.manifestUrlString=Me(this.manifestUrlString,C,fe.DASH_CMAF_OFFSET_P)}(p||v||S)&&(await this.updateLive(),n=0)}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,xe({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Je.REPRESENTATIOS_READY)}.bind(this));initBuffer(){w(this.element),this.state$.setState(Je.RUNNING),this.subscription.add(O(...Ts.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ti(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Re.VIDEO]:this.videoBufferManager,[Re.AUDIO]:this.audioBufferManager,[Re.TEXT]:null}[e]?.switchTo(t)}seek(e,t){w(this.element),w(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ti(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Je.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Yt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};class en{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class tn{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:s,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var sn=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,
|
|
37
|
+
`}),T}return d?.recordSwitch(F),F};var Fe=r=>new URL(r).hostname;const Gr=300,vi=(r,e=Gr)=>new zi(t=>{const{width:i,height:s}=r.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const a=new ResizeObserver(lr(n=>{const o=n[0];if(!o)return;let c,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,c=o.contentBoxSize[0].inlineSize):o.contentRect&&(c=o.contentRect.width,d=o.contentRect.height),P(c)&&P(d)&&t.next({width:c,height:d})},e));return a.observe(r),()=>a.disconnect()});class $i{onDroopedVideoFramesLimit$=new I;subscription=new se;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new I;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(M(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Yt(this.droppedFramesChecker.checkTime).pipe(K(()=>this.playing),K(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(je(this.droppedFramesChecker.checkTime)),i=O(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Ht(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,s=t-this.prevDroppedVideoFrames,a=1-(i-s)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&Kt(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])=>Ri(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 ci={};var X;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(X||(X={}));const Ee=(r,e)=>new zi(t=>{const i=s=>t.next(s);return r.on(e,i),()=>r.off(e,i)});class ps{subscription=new se;videoState=new de(X.DOWNLOADING_LIB);video;player;params;textTracksManager=new nt;droppedFramesManager=new $i;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 ki;constructor(e){this.video=St(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category: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||(ci.MediaPlayer=s.MediaPlayer,ci.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){D(ci.MediaPlayer,"dashjs not loaded"),D(ci.Debug,"dashjs not loaded"),this.player=ci.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?qi(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Rr(this.player),Pr(this.player),this.params.tuning.requestQuick&&Lr(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:g})},s=(g,E)=>this.subscription.add(g.subscribe(E,i));s(vi(this.video),this.elementSize$),s(Ee(this.player,"error").pipe(A(g=>{const E=typeof g.error=="object"?g.error.code:g.error,x=typeof g.error=="object"?g.error.message:void 0;return{id:`DashJS#${E}`,message:x}})),e.error$),s(Ee(this.player,"playbackError").pipe(A(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const a=Ee(this.player,"qualityChangeRendered").pipe(K(({mediaType:g})=>g==="video"),A(({newQuality:g})=>this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===g)?.track));a.pipe(K(P)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(K(({to:g})=>g===X.STREAM_INITIALIZED),be()).subscribe(()=>{this.subscription.add(at(t.videoTrack,()=>{const g=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===g)?.track},g=>{if(Y(g))return;const E=this.videoTracks$.getValue().find(({track:x})=>x.id===g.id)?.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:a,onError:i}))},i)),this.subscription.add(at(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,g=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:g}}}}),{onError:i})),s(Ee(this.player,"bufferStateChanged").pipe(K(({mediaType:g})=>g==="video"),A(({state:g})=>g==="bufferStalled")),e.isBuffering$),s(Ee(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:E}})=>{const x=this.player.getDashMetrics(),H=x.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),q=x.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type")??Ti.HTTP1,F={1:!0,0:!1}[H]??void 0;this.params.output.httpConnectionType$.next(q),this.params.output.httpConnectionReused$.next(F),e.hostname$.next(Fe(E))}),s(Ee(this.player,"streamInitialized"),({streamInfo:{duration:g,manifestInfo:{isDynamic:E,availableFrom:x}}})=>{this.isLive$.next(E),this.availableFrom$.next(x.getTime()),E||e.duration$.next(g);const H=[],q=this.player.getQualityFor("video");let F;for(const G of this.player.getBitrateInfoListFor("video")){const T=G.qualityIndex.toString(10),V=It(G),z=G.bitrate/1e3,te={width:G.width,height:G.height},ye=this.frameRatesByFrameHeight[G.height];if(V){const ke={id:T,quality:V,bitrate:z,size:te,fps:ye};H.push({track:ke,bitrateInfo:G}),G.qualityIndex===q&&(F=ke)}}this.videoTracks$.next(H),e.availableVideoTracks$.next(H.map(({track:G})=>G)),F&&e.currentVideoTrack$.next(F),this.videoState.setState(X.STREAM_INITIALIZED),this.videoState.startTransitionTo(X.READY)}),s(Ee(this.player,"fragmentLoadingCompleted"),({request:g})=>{if(!g.requestEndDate||!g.firstByteDate||!g.bytesLoaded)return;const E=g.requestEndDate.getTime()-g.firstByteDate.getTime(),x=g.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(x,E)}),s(O(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const g=this.params.dependencies.throughputEstimator.throughput$.getValue(),E=Gt(this.videoTracks$.getValue().map(({track:q})=>q),{container:this.elementSize$.getValue(),throughput:g,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),x=t.autoVideoTrackLimits.getTransition();x&&e.autoVideoTrackLimits$.next(x.to);const H=this.videoTracks$.getValue().find(({track:q})=>q===E);H?.bitrateInfo&&this.player.setQualityFor("video",H?.bitrateInfo.qualityIndex,!1)}),s(xe({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(K(P))}).pipe(K(({isLive:g})=>g),A(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const n=Ee(this.player,"playbackTimeUpdated").pipe(A(({time:g})=>g??0));s(xe({availableFrom:this.availableFrom$.pipe(K(P)),currentTime:n}),({availableFrom:g,currentTime:E})=>this.params.output.liveTime$.next(g+E*1e3)),s(n.pipe(K(()=>this.isLive$.getValue()===!1)),e.position$),s(Ee(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(Ee(this.player,"playbackEnded"),e.endedEvent$),s(Ee(this.player,"playbackProgress").pipe(A(()=>Vs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(Ee(this.player,"playbackPlaying"),()=>{this.videoState.setState(X.PLAYING),R(t.playbackState,f.PLAYING)}),s(Ee(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(Ee(this.player,"playbackPaused"),()=>{this.videoState.setState(X.PAUSED),R(t.playbackState,f.PAUSED)}),s(Ee(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===X.READY&&this.videoState.setState(X.READY)}),s(this.isLive$,e.isLive$),s(vi(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=xr(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(be()),e.firstBytesEvent$),s(Ee(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(xe({isLive:this.isLive$,isShort:e.duration$.pipe(A(g=>g<60))}),({isLive:g,isShort:E})=>{const x=!g&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:x}}})}),s(n.pipe(K(g=>g>this.params.tuning.insufficientBufferRuleMargin),be()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Ee(this.player,"manifestLoaded").pipe(be()).subscribe(()=>{this.subscription.add(Ee(this.player,"playbackPlaying").pipe(be(),Zt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(Ee(this.player,"manifestLoaded"),g=>{if(g.data?.Period?.AdaptationSet){const E=[];for(const x of g.data?.Period?.AdaptationSet)if(x.contentType==="text"){const H=x.Representation?.id,q=new URL(x.Representation?.BaseURL,g.data?.baseUri).toString(),F="internal",G=x.lang;E.push({id:H,url:q,type:F,language:G})}t.internalTextTracks.startTransitionTo(E)}}),this.subscription.add(Ct(this.video,t.isLooped,i));const{volumeState$:l,looped$:p,playbackRateState$:S,inPiP$:v,inFullscreen$:b,pause$:w,playing$:C}=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:C,pause$:w,tracks$:this.videoTracks$.pipe(A(g=>g.map(({track:E})=>E)))}),this.subscription.add(gt(this.video,t.volume,l,i)),this.subscription.add(l.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(wt(this.video,t.playbackRate,S,i)),this.subscription.add(v.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(X.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(X.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=Oe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,fe.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(X.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(X.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===X.DOWNLOADING_LIB||e===X.STREAM_INITIALIZED))switch(i?.to!==f.PAUSED&&s.state===j.Requested&&e!==X.STOPPED&&t!==f.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case f.STOPPED:{switch(e){case X.STOPPED:break;case X.PLAYING:case X.PAUSED:case X.READY:this.stop();break;default:N(e)}break}case f.READY:{switch(e){case X.STOPPED:this.prepare();break;case X.PLAYING:case X.PAUSED:case X.READY:break;default:N(e)}break}case f.PLAYING:{switch(e){case X.PLAYING:break;case X.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case X.READY:this.play();break;case X.STOPPED:this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case X.PLAYING:this.pause(),this.liveOffset.pause();break;case X.PAUSED:break;case X.READY:this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case X.STOPPED:this.prepare();break;default:N(e)}break}default:N(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}bt(this.video),this.params.output.element$.next(void 0)}}var ai=r=>{switch(r){case"mobile":return Je.Q_144P;case"lowest":return Je.Q_240P;case"low":return Je.Q_360P;case"sd":case"medium":return Je.Q_480P;case"hd":case"high":return Je.Q_720P;case"fullhd":case"full":return Je.Q_1080P;case"quadhd":case"quad":return Je.Q_1440P;case"ultrahd":case"ultra":return Je.Q_2160P}};const ms=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))};var Dt=async r=>{const e=r.muted;try{await r.play()}catch(t){if(!ms(t))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(i){return ms(i)&&(r.muted=!1,console.warn(i)),!1}}return!0};function Me(){return ne()}function Hs(r){return Me()-r}function gs(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,c=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return c&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function zr(r,e,t){const i=(...s)=>{t.apply(null,s),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ii(r,e,t,i){const s=window.XMLHttpRequest;let a,n,o,c=!1,d=0,h,u,l=!1,p="arraybuffer",S=7e3,v=2e3,b=()=>{if(c)return;D(h);const z=Hs(h);let te;if(z<v){te=v-z,setTimeout(b,te);return}v*=2,v>S&&(v=S),n&&n.abort(),n=new s,H()};const w=z=>(a=z,V),C=z=>(u=z,V),g=()=>(p="json",V),E=()=>{if(!c){if(--d>=0){b(),i&&i();return}c=!0,u&&u(),t&&t()}},x=z=>(l=z,V),H=()=>{h=Me(),n=new s,n.open("get",r);let z=0,te,ye=0;const ke=()=>(D(h),Math.max(h,Math.max(te||0,ye||0)));if(a&&n.addEventListener("progress",U=>{const re=Me();a.updateChunk&&U.loaded>z&&(a.updateChunk(ke(),U.loaded-z),z=U.loaded,te=re)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(c)return;D(n);const U=n.status;if(U>=200&&U<300){if(n.response.byteLength&&a){const re=n.response.byteLength-z;re&&a.updateChunk&&a.updateChunk(ke(),re)}u&&u(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),l){const U=()=>{D(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=Me(),n.removeEventListener("readystatechange",U))};n.addEventListener("readystatechange",U)}return n.responseType=p,n.send(),V},V={withBitrateReporting:w,withParallel:x,withJSONResponse:g,withRetryCount:z=>(d=z,V),withRetryInterval:(z,te)=>(P(z)&&(v=z),P(te)&&(S=te),V),withTimeout:z=>(o=z,V),withFinally:C,send:H,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return V}const qr=100,Wr=2e3,Qr=500;let jr=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-Qr;if(t-e>Wr){let i=0,s=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,s+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const c=a.bytes*n/o;s+=c,a.start=t,a.bytes-=c}}}if(s>0&&i>0){const a=s*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>qr&&(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 Jr{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=Me(),s=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=c=>{e._complete=1,e._responseData=c,e._downloadTime=Me()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ii(t,a,()=>s("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Me()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Me();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,s){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Pi=1e4,xi=3,Xr=300,Kr=2e3,Zr=6e4,ea=10,ta=1,ia=500;class sa{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 jr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=gs(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=gs(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||P(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{zr(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Jr(xi,Pi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let a=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const E=a&&(!h||h===this.rep);return E||t("Not running!"),E},l=(E,x,H)=>{c&&c.abort(),c=Ii(this.urlResolver.resolve(E,!1),x,H,()=>this._retryCallback()).withTimeout(Pi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xi).withFinally(()=>{c=null}).send()},p=(E,x,H)=>{D(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),x,H,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=E=>{const x=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${x}=>${E}`),i.playbackRate=E)},v=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const H=Me()-1e4;let q=0;for(let G=0;G<this.bufferStates.length;G++){const T=this.bufferStates[G];E=Math.min(E,T.buf),T.ts<H&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${E} drop=${q} jitter=${this.sourceJitter}`);let F=E-ta;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?S(1.15):F>1?S(1.1):F>.3?S(1.05):S(1)}},w=E=>{let x;const H=()=>x&&x.start?x.start.length:0,q=U=>x.start[U]/1e3,F=U=>x.dur[U]/1e3,G=U=>x.fragIndex+U,T=(U,re)=>({chunkIdx:G(U),startTS:q(U),dur:F(U),discontinuity:re}),V=()=>{let U=0;if(x&&x.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,pe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,$e=re;this.sourceJitter>1&&($e+=this.sourceJitter-1);let Be=x.dur.length-1;for(;Be>=0&&($e-=x.dur[Be],!($e<=0));--Be);U=Math.min(Be,x.dur.length-1-pe),U=Math.max(U,0)}return T(U,!0)},z=U=>{const re=H();if(!(re<=0)){if(P(U)){for(let pe=0;pe<re;pe++)if(q(pe)>U)return T(pe)}return V()}},te=U=>{const re=H(),pe=U?U.chunkIdx+1:0,$e=pe-x.fragIndex;if(!(re<=0)){if(!U||$e<0||$e-re>ea)return t(`Resync: offset=${$e} bChunks=${re} chunk=`+JSON.stringify(U)),V();if(!($e>=re))return T(pe-x.fragIndex,!1)}},ye=(U,re,pe)=>{d&&d.abort(),d=Ii(this.urlResolver.resolve(U,!0,this.lowLatency),re,pe,()=>this._retryCallback()).withTimeout(Pi).withRetryCount(xi).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(U,re)=>{ye(E,pe=>{if(!u())return;x=pe;const $e=!!x.lowLatency;$e!==this.lowLatency&&v($e);let Be=0;for(let ot=0;ot<x.dur.length;++ot)Be+=x.dur[ot];Be>0&&(D(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Be/x.dur.length)),s({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,U(z(re))},()=>this._handleNetworkError())},nextChunk:te}},C=()=>{a=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),D(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:E=>{const{videoElement:x,logger:H}=this.params;let q=w(e.jidxUrl),F,G,T,V,z=0,te,ye,ke;const U=()=>{te&&(clearTimeout(te),te=void 0);const ae=Math.max(ia,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=z+ae,Ve=Me(),De=Math.min(1e4,we-Ve);z=Ve;const vt=()=>{d||u()&&q.seek(()=>{u()&&(z=Me(),re(),U())})};De>0?te=window.setTimeout(()=>{this.paused?U():vt()},De):vt()},re=()=>{let ae;for(;ae=q.nextChunk(V);)V=ae,oi(ae);const we=q.nextChunk(T);if(we){if(T&&we.discontinuity){H("Detected discontinuity; restarting playback"),this.paused?U():(C(),this._initPlayerWith(e));return}ot(we)}else U()},pe=(ae,we)=>{if(!u()||!this.sourceBuffer)return;let Ve,De,vt;const Te=Ge=>{window.setTimeout(()=>{u()&&pe(ae,we)},Ge)};if(this.sourceBuffer.updating)H("Source buffer is updating; delaying appendBuffer"),Te(100);else{const Ge=Me(),Ae=x.currentTime;!this.paused&&x.buffered.length>1&&ye===Ae&&Ge-ke>500&&(H("Stall suspected; trying to fix"),this._fixupStall()),ye!==Ae&&(ye=Ae,ke=Ge);const Pe=this._getBufferSizeSec();if(Pe>30)H(`Buffered ${Pe} seconds; delaying appendBuffer`),Te(2e3);else try{this.sourceBuffer.appendBuffer(ae),this.videoPlayStarted?(this.bufferStates.push({ts:Ge,buf:Pe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(dt){if(dt.name==="QuotaExceededError")H("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&(Ve=this.sourceBuffer.buffered.start(0),De=Ae,De-Ve>4&&this.sourceBuffer.remove(Ve,De-3)),Te(1e3);else throw dt}}},$e=()=>{G&&F&&(H([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(T)]),pe(G,function(){G=null,re()}))},Be=ae=>e.fragUrlTemplate.replace("%%id%%",ae.chunkIdx),ot=ae=>{u()&&p(Be(ae),(we,Ve)=>{if(u()){if(Ve/=1e3,G=we,T=ae,n=ae.startTS,Ve){const De=Math.min(10,ae.dur/Ve);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}$e()}},()=>this._handleNetworkError())},oi=ae=>{u()&&(D(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Be(ae),!1)))},zt=ae=>{u()&&(e.cachedHeader=ae,pe(ae,()=>{F=!0,$e()}))};a=!0,q.seek(ae=>{if(u()){if(z=Me(),!ae){U();return}V=ae,!Y(E)||ae.startTS>E?ot(ae):(T=ae,re())}},E),e.cachedHeader?zt(e.cachedHeader):l(e.headerUrl,zt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),P(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,D(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return P(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let l,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(p=this._getBufferSizeSec(),S=u/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}l=this._selectQuality(u),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${u}`)},a=(()=>({updateChunk:(l,p)=>{const S=Me();if(this.chunkRateEstimator.addInterval(l,S,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-l,speed:b}),!0}},get:()=>{const l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=a.get();if(u&&o&&this.autoQuality){if(c&&u>o&&Hs(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,l)=>{const p=a.updateChunk(u,l);return p&&d(),p},notifySwitch:u=>{const l=Me();u<o&&(n=l),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=Ii(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Pi).withRetryCount(xi).withRetryInterval(Xr,Kr).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Dt(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,a=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&s.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=d,o.push(c))}),o.sort(function(c,d){return c.video&&d.video?d.video.height-c.video.height:d.bitrate-c.bitrate}),o):(i({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Zr))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var J;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(J||(J={}));const ra=[J.PAUSED,J.PLAYING,J.READY],aa=[J.PAUSED,J.PLAYING,J.READY];class na{subscription=new se;video;videoState=new de(J.STOPPED);dash;representations$=new m([]);textTracksManager=new nt;droppedFramesManager=new $i;maxSeekBackTime$=new m(1/0);zeroTime$=new m(void 0);liveOffset=new ki;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:L.WTF,message:"DashLiveProvider internal logic error",thrown:s})};O(this.videoState.stateChangeStarted$.pipe(A(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(s)}`})}),this.video=St(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=yt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(A(s=>s.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===j.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(J.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(le(),A(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(xe({zeroTime:this.zeroTime$.pipe(K(P)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:a})=>this.params.output.liveTime$.next(s+a*1e3),t)).add(Ct(this.video,this.params.desiredState.isLooped,t)).add(gt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(wt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const a=s&&fr(s);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case J.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(f.STOPPED);break;case J.MANIFEST_READY:case J.READY:this.params.desiredState.playbackState.getTransition()?.to===f.READY&&this.params.desiredState.playbackState.setState(f.READY);break;case J.PAUSED:this.params.desiredState.playbackState.setState(f.PAUSED);break;case J.PLAYING:this.params.desiredState.playbackState.setState(f.PLAYING);break;default:return N(s.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ne(["init"])).pipe(je(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}createLiveDashPlayer(){const e=new sa({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&P(t)?t:Gt(e.map(({track:d})=>d),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=s?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(n||a!==o)&&this.setVideoTrack(s),c&&this.setAutoQuality(i),n||c||a!==o){const d=e.find(({track:h})=>h.id===a)?.representation;D(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;D(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===f.PAUSED&&i===J.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Oe(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:L.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const a=s.name??s.index.toString(10),n=ai(s.name)??It(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:a,quality:n,bitrate:o,size:c};i.push({track:d,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===J.MANIFEST_READY&&this.videoState.setState(J.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),P(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(J.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(aa.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==f.PAUSED&&a.state===j.Requested&&ra.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case J.STOPPED:this.videoState.startTransitionTo(J.MANIFEST_READY),this.dash.attachSource(Oe(this.params.source.url));return;case J.MANIFEST_READY:this.videoState.startTransitionTo(J.READY),this.prepare();break;case J.READY:if(i===f.PAUSED)this.videoState.setState(J.PAUSED);else if(i===f.PLAYING){this.videoState.startTransitionTo(J.PLAYING);const c=s?.from;c&&c===f.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(J.PAUSED)})}return;case J.PLAYING:i===f.PAUSED&&(this.videoState.startTransitionTo(J.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case J.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(J.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(J.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Oe(this.params.source.url,c))}return;default:return N(e)}}}var cs=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?Ti.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},Ye=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){const s=r.start(i)*1e3,a=r.end(i)*1e3;s<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const oa=r=>{const e=document.createElement("a");return e.href=r,e.origin},da=r=>{const e=document.createElement("a");return e.href=r,e.host};class Ys{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,a,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(this._xhr){if(this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(i=>i.split(":").map(s=>s.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(da(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 Bi{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let a=0;for(let n=0,o=s.length;n<o;n++)a+=s.end(n)-s.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,a,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,l=0;const p=v=>{s(Bi._str2ua(v.substr(c))),c=v.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=Rt(S)),this._lastXhr=new Ys(S,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const b=Date.now()-d;this._params.onBandwidthChange({size:v.length,duration:b,speed:8*v.length/(b/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),a?.()},v=>{if(v.length-c>o&&p(v),u===0){u=Date.now();return}l=v.length-h;const b=Date.now()-u;l>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:l,duration:b,speed:8*l/(b/1e3)}),l=0,h=v.length,u=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},n,(v,b,w)=>this._params.onError(v,b,w))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Bi._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 ca{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},s=t.exec(e),a=s?.[1]==="-"?-1:1,n={years:i(s?.[2],a),months:i(s?.[3],a),weeks:i(s?.[4],a),days:i(s?.[5],a),hours:i(s?.[6],a),minutes:i(s?.[7],a),seconds:i(s?.[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Rt(i)),new Ys(i,t,s=>{this.attachManifest(s,t,oa(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,a,n)=>this._params.onError(s,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,h)=>{const u=d.attributes.getNamedItem(h);return u?u.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),l=h&&h.getElementsByTagName("Initialization")[0],p=l&&n(l,"range").split("-");if(!p||!u){const g=d.parentElement;if(g?.getAttribute("contentType")==="text"){const E=d.getAttribute("id")??void 0,x=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,H=g.getAttribute("lang")??void 0;x&&c.push({id:E,url:x,language:H})}return}const S=.1,v=Number(d.attributes.getNamedItem("bandwidth")?.value),b=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let w;const C=d.attributes.getNamedItem("frameRate")?.value??void 0;w=C?qi(C):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:v,baseURL:b,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:w,bufferSize:S*v/8,bufferLength:S,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:h,url:u})=>{const l=document.createElement("track");u&&l.setAttribute("src",u),d&&l.setAttribute("id",d),h&&l.setAttribute("srclang",h),this._video.appendChild(l)}),this._representations.sort((d,h)=>h.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:c})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let a=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,a);const n=new DataView(s.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let c=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const h=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let l=0;l<h;l+=1){const p=d+(n.getUint32(a,!1)&2147483647),S=c+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:c/o,toTime:S/o,fromOffset:d,toOffset:p-1}),d=p,c=S}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let s,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const h=this._appendVector[String(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}u=p.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},u*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},c=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Bi({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",c),i.removeEventListener("webkitsourceopen",c)};i.addEventListener("sourceopen",c,!1),i.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(s.toTime<i.to+a){const n=this._findRef(s.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,n.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||Y(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let i;for(let s=0;s<t.length;s++){const a=t[s];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!i||a.fromTime<i.fromTime)&&(i=a)}if(!i){const s=t[t.length-1];if(e>s.toTime)return s}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>i&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Z;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Z||(Z={}));const ua=[Z.PAUSED,Z.PLAYING];class ha{videoState=new de(Z.STOPPED);subscription=new se;video;buffer;dash;representations$=new m([]);currentRepresentation$=new m(void 0);params;textTracksManager=new nt;droppedFramesManager=new $i;elementSize$=new m(void 0);dashLiteEvents={idxRequestPing$:new I,responseHeaders$:new I,manifestReady$:new I,representationPlay$:new I,error$:new I};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),O(this.videoState.stateChangeStarted$.pipe(A(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Or(this.video),this.dash=new ca({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:s,category:L.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:L.WTF,message:"DashProvider internal logic error",thrown:o})},s=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},a=yt(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{Y(this.params.desiredState.seekState.getState().state!==j.Applying)&&(this.videoState.getState()===Z.PLAYING||this.videoState.getState()===Z.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(wt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(A(o=>o.map(({track:c})=>c)))}),n(vi(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),R(this.params.desiredState.playbackState,f.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Z.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(A(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(O(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).pipe(A(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState()?.id,u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),p=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let S;if(!p&&P(h))S=h;else{const v=Ye(this.video.buffered,this.video.currentTime*1e3),b=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(v/b,1);S=Gt(c.map(({track:g})=>g),{container:l,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:c.find(({representation:g})=>g===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const C=t.autoVideoTrackLimits.getTransition();C&&e.autoVideoTrackLimits$.next(C.to)}return P(S)?c.find(({track:v})=>v.id===S)?.representation:void 0}),le()).subscribe(this.currentRepresentation$,i)).add(xe({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(K(o=>o.to===Z.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(K(P))}).pipe(be()).subscribe(()=>this.videoState.setState(Z.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(K(P),le((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=Ye(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!s())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Fe(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=cs(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(be(),Zt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(K(P)).subscribe(this.handleRepresentationPlay,i)).add(O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return N(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const a=s.name??s.id??s.height.toString(10),n=(s.name&&ai(s.name))??It(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:a,quality:n,bitrate:o,size:c,fps:d};i.push({track:h,representation:s})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),t?.length>0){const s=[];for(const a of t){const n=a.id||`${a.language}_${Date.now()}`;s.push({id:n,type:"internal",url:a.url||"",language:a.language,isAuto:a.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(Z.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return D(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i===f.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(!t)switch(s?.to!==f.PAUSED&&a.state===j.Requested&&ua.includes(e)&&this.seek(a.position,a.forcePrecise),e){case Z.STOPPED:this.videoState.startTransitionTo(Z.MANIFEST_LOADED),this.prepare();return;case Z.MANIFEST_LOADED:this.videoState.startTransitionTo(Z.INITIAL_REPRESENTATION_SELECTED);return;case Z.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Z.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Z.METADATA_LOADED:this.videoState.startTransitionTo(Z.READY),this.dash.updateRefsForCurrentTime();return;case Z.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Z.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}var Ie;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Ie||(Ie={}));var _i;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(_i||(_i={}));var Ze;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Ze||(Ze={}));var ee;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(ee||(ee={}));var ei;(function(r){r.MP4="mp4",r.WEBM="webm"})(ei||(ei={}));var Mi;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Mi||(Mi={}));var me;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(me||(me={}));var ti=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const la=16;let Gs=!1;try{Gs=Gi().browser===ns.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=la}catch(r){console.error(r)}let fa=class{bufferFull$=new I;error$=new I;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;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:N(t)}}};var Oi=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};let Tt=class{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}},zs=class extends Tt{},pa=class extends Tt{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}},ma=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},ga=class extends Tt{data;constructor(e){super(e),this.data=this.content}},Ai=class extends Tt{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},Sa=class extends Ai{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}},ba=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},ya=class extends Tt{parseChildrenBoxes(){return ni(this.content)}};var Vt;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Vt||(Vt={}));let Ta=class extends Ai{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Vt.MONOSCOPIC;break;case 1:this.stereoMode=Vt.TOP_BOTTOM;break;case 2:this.stereoMode=Vt.LEFT_RIGHT;break;case 3:this.stereoMode=Vt.STEREO_CUSTOM;break;case 4:this.stereoMode=Vt.RIGHT_LEFT;break}this.cursor+=1}},va=class extends Ai{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},Ea=class extends Ai{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},ka=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},$a=class extends Ai{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()}},Aa=class extends Tt{parseChildrenBoxes(){return ni(this.content)}},wa=class extends Tt{parseChildrenBoxes(){return ni(this.content)}};const Da={ftyp:pa,moov:ma,mdat:ga,sidx:Sa,trak:ba,mdia:ka,tkhd:$a,minf:Aa,sv3d:ya,st3d:Ta,prhd:va,proj:wa,equi:Ea,unknown:zs};let Pa=class{createBox(e,t){const i=Da[e];return i?new i(t):new zs(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Wi.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Wi=new Pa;function pi(r,e){const t=new TextDecoder("ascii");let i=r.byteOffset,s=[];for(;i<r.byteLength;){const a=t.decode(new DataView(r.buffer,i,1));if(a===e[s.length]?s.push(a):s=[],s.length===4&&s.join("")===e){const o=new DataView(r.buffer,i-7,4).getUint32(0);return i-7+o>r.byteLength?null:Wi.createBox(e,new DataView(r.buffer,i-7))}i++}return null}function xa(r,e){const t=[];let i=0;for(;i<r.byteLength;){const s=pi(new DataView(r.buffer,r.byteOffset+i,r.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function ni(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Wi.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const La=new TextDecoder("ascii"),Ra=r=>La.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Ia=r=>{const e=Wi.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:ee.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Ca=r=>{const e=xa(r,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(r.buffer,r.byteOffset,t)}return null},Ba=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Mi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(pi(r,"sv3d")){e.is3dVideo=!0;const i=pi(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=pi(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=pi(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},_a={validateData:Ra,parseInit:Ba,getIndexRange:()=>{},parseSegments:Ia,parseFeedableSegmentChunk:Ca};var k;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(k||(k={}));var B;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(B||(B={}));const Ss={[k.EBML]:{type:B.Master},[k.EBMLVersion]:{type:B.UnsignedInteger},[k.EBMLReadVersion]:{type:B.UnsignedInteger},[k.EBMLMaxIDLength]:{type:B.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:B.UnsignedInteger},[k.DocType]:{type:B.String},[k.DocTypeVersion]:{type:B.UnsignedInteger},[k.DocTypeReadVersion]:{type:B.UnsignedInteger},[k.Void]:{type:B.Binary},[k.Segment]:{type:B.Master},[k.SeekHead]:{type:B.Master},[k.Seek]:{type:B.Master},[k.SeekID]:{type:B.Binary},[k.SeekPosition]:{type:B.UnsignedInteger},[k.Info]:{type:B.Master},[k.TimestampScale]:{type:B.UnsignedInteger},[k.Duration]:{type:B.Float},[k.Tracks]:{type:B.Master},[k.TrackEntry]:{type:B.Master},[k.Video]:{type:B.Master},[k.Projection]:{type:B.Master},[k.ProjectionType]:{type:B.UnsignedInteger},[k.ProjectionPrivate]:{type:B.Master},[k.Chapters]:{type:B.Master},[k.Cluster]:{type:B.Master},[k.Timestamp]:{type:B.UnsignedInteger},[k.SilentTracks]:{type:B.Master},[k.SilentTrackNumber]:{type:B.UnsignedInteger},[k.Position]:{type:B.UnsignedInteger},[k.PrevSize]:{type:B.UnsignedInteger},[k.SimpleBlock]:{type:B.Binary},[k.BlockGroup]:{type:B.Master},[k.EncryptedBlock]:{type:B.Binary},[k.Attachments]:{type:B.Master},[k.Tags]:{type:B.Master},[k.Cues]:{type:B.Master},[k.CuePoint]:{type:B.Master},[k.CueTime]:{type:B.UnsignedInteger},[k.CueTrackPositions]:{type:B.Master},[k.CueTrack]:{type:B.UnsignedInteger},[k.CueClusterPosition]:{type:B.UnsignedInteger},[k.CueRelativePosition]:{type:B.UnsignedInteger},[k.CueDuration]:{type:B.UnsignedInteger},[k.CueBlockNumber]:{type:B.UnsignedInteger},[k.CueCodecState]:{type:B.UnsignedInteger},[k.CueReference]:{type:B.Master},[k.CueRefTime]:{type:B.UnsignedInteger}},qs=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ni(r,t),s=i in Ss,a=s?Ss[i].type:B.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Ni(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Ni=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ft=(r,e)=>{switch(e){case B.SignedInteger:return r.getInt8(0);case B.UnsignedInteger:return Ni(r);case B.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case B.String:return new TextDecoder("ascii").decode(r);case B.UTF8:return new TextDecoder("utf-8").decode(r);case B.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case B.Master:return r;case B.Binary:return r;default:N(e)}},ii=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=qs(i);if(!e(s))return;s.type===B.Master&&ii(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},Ma=r=>{if(r.getUint32(0)!==k.EBML)return!1;let e,t,i;const s=qs(r);return ii(s.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=ft(o,n):a===k.DocType?t=ft(o,n):a===k.DocTypeReadVersion&&(i=ft(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ws=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],Oa=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],Na=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ii(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===k.SeekID){const b=ft(S,p);d=Ni(b)}else l!==k.SeekPosition&&(d=void 0);return l===k.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===k.Info?a=!0:l===k.SeekHead?n=!0:l===k.TimestampScale?i=ft(S,p):l===k.Duration?s=ft(S,p):l===k.SeekPosition&&d===k.Cues?c=ft(S,p):l===k.Tracks?ii(S,({tag:b,type:w,value:C})=>b===k.ProjectionType?(h=ft(C,w)===1,!1):!0):a&&n&&Ws.includes(l)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:u,projectionType:Mi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Fa=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Va=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ii(r,({tag:o,type:c,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&s(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=ft(d,c));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=ft(d,c));break;default:t&&Ws.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:ee.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Ua=r=>{let e=0,t=!1;try{ii(r,i=>i.tag===k.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Oa.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Ha={validateData:Ma,parseInit:Na,getIndexRange:Fa,parseSegments:Va,parseFeedableSegmentChunk:Ua},Qs=1e4,Ya=3e4,Ga=5e3,za=Qs,qa=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?ai(a):void 0)??It({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},Wa=({id:r,bitrate:e})=>({id:r,bitrate:e}),Qa=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},ja=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),Li=r=>{const e=[];let t=0,i=r.length-1;for(;t<Qs&&i>=0;)e.unshift(r[i]),t+=r[i].time.to-r[i].time.from,i--;return e};let bs=class{onLastSegment$=new m(!1);fullyBuffered$=new m(!1);playingRepresentation$=new m(void 0);playingRepresentationInit$=new m(void 0);error$=new I;gaps=[];isSeekingLive=!1;subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new AbortController;destroyAbortController=new AbortController;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,s,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1,manifest:d}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!d?.dynamic,this.container=i,i){case ei.MP4:this.containerParser=_a;break;case ei.WEBM:this.containerParser=Ha;break;default:N(i)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);D(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new fa(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);D(i,"No init buffer for starting representation"),D(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);D(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),D(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();P(a)&&(this.searchGaps(i,t),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Ye(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Oi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Ye(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===ee.FED&&!o.length&&Ye(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;for(const s of e)s.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from}),i=s.time.to;P(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d)return;const h=Li(d.segmentReference.segments);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);D(i);const s=Li(i.segmentReference.segments),a=this.initData.get(i.id);if(D(a,"No init buffer for starting representation"),D(s,"No segments for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t)return;const i=t.segmentReference.segments.map(o=>({...o,status:ee.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.round(a)>=Math.round(o.time.from)&&Math.round(a)<=Math.round(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=Li(i);this.segments.set(t.id,[...o])}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,w=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+w||p<=i+w;return(u===ee.NONE||u===ee.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!ti(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==Ze.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===ee.NONE||l.status===ee.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ze.BYTE_RANGE:{s=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Ze.TEMPLATE:{const d=e.at(0);s=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:N(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await oe(c,async function*(){const d=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(s,{range:a,onProgress:(d,h)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,h,c)}catch(u){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:c,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(d)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&P(i)&&(t=Ye(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,s,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=u=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),u.segment.status=ee.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const l of this.representations.values())if(l.id!==t)for(const p of this.segments.get(l.id)??[])p.status===ee.FED&&p.time.from===u.segment.time.from&&p.time.to===u.segment.time.to&&(p.status=ee.NONE);this.activeSegments.delete(u),this.detectGapsWhenIdle(t,[u.segment])},c=this.representations.get(t);if(!c)return;const d=c.segmentReference.type,h=e.byteLength;for(const u of this.activeSegments){const{segment:l}=u,p=d===Ze.BYTE_RANGE,S=p?l.byte.to-l.byte.from+1:h;if(u.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const b=p?l.byte.from-i:0,w=p?l.byte.to-i:e.byteLength,C=b<s,g=w<=s;if(l.status===ee.DOWNLOADING&&C&&g){l.status=ee.DOWNLOADED,this.activeSegments.delete(u);const E=new DataView(e.buffer,e.byteOffset+b,S);this.sourceBufferTaskQueue.append(E,a).then(x=>x&&!a.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&C&&(u.loadedBytes=Math.min(S,s-b),u.loadedBytes>u.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+u.feedingBytes,u.loadedBytes-u.feedingBytes),x=u.loadedBytes===S?E:this.containerParser.parseFeedableSegmentChunk(E);x?.byteLength&&(l.status=ee.PARTIALLY_FED,u.feedingBytes+=x.byteLength,this.sourceBufferTaskQueue.append(x,a).then(H=>{if(a.aborted)n();else if(H)u.fedBytes+=x.byteLength,u.fedBytes===S&&o(u);else{if(u.feedingBytes<S)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=gi(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?Li(h):h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h="size"in d?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===ee.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===ee.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===ee.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===ee.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=ee.PARTIALLY_EJECTED:s.status=ee.NONE)}}};var Jt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Jt||(Jt={}));let Ja=class{throughputEstimator;requestQuic;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);abortAllController=new AbortController;subscription=new se;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Rt(t));const i=yield fetch(t,{signal:this.abortAllController.signal}).catch(ui);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Jt.HEADER:Jt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(i)switch(t){case Jt.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case Jt.PARAM:{const T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:N(t)}this.requestQuic&&(c=Rt(c));let h=this.abortAllController.signal,u;if(n){const T=new AbortController;if(u=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{T.abort()}catch(V){ui(V)}}),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(V){ui(V)}h=T.signal}const l=ne(),p=yield fetch(c,{priority:a,headers:d,signal:h}).catch(ui),S=ne();if(this.throughputEstimator?.addRawRtt(S-l),!p)return u?.unsubscribe(),null;if(!p.ok||!p.body)return u?.unsubscribe(),Promise.reject(new Error(`Fetch error ${p.status}: ${p.statusText}`));this.onHeadersReceived(p.headers);const v=parseInt(p.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!v){const T=yield p.arrayBuffer();return this.throughputEstimator?.addRawSpeed(T.byteLength,ne()-S),s?.(new DataView(T),T.byteLength),u?.unsubscribe(),T}if(!s&&!o)return u?.unsubscribe(),p.arrayBuffer();const[b,w]=p.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(w);let g=0;const E=new ArrayBuffer(v),x=new Uint8Array(E),H=new DataView(E);let q=!1;const F=T=>{u?.unsubscribe(),q=!0,ui(T)},G=oe(h,async function*({done:T,value:V}){if(g===0&&this.lastRequestFirstBytes$.next(ne()-l),h.aborted){u?.unsubscribe();return}!T&&V&&(x.set(V,g),g+=V.byteLength,s?.(H,g),yield C?.read().then(G,F))}.bind(this));return yield C?.read().then(G,F),u?.unsubscribe(),q?null:E}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ze.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ze.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ze.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const w=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!w)return null;v=new DataView(w)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==Ze.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(n=>({...n,status:ee.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))};const ui=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},ys=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ji=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},Xa=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=ys(l);else if(p){const g=ys(p);P(g)&&(u=g)}else v&&(u=parseInt(v,10));let b=0;const w=a.getAttribute("profiles")?.split(",")??[],C=w.includes(_i.WEBM_AS_IN_FFMPEG)||w.includes(_i.WEBM_AS_IN_SPEC)?ei.WEBM:ei.MP4;for(const g of o){const E=g.getAttribute("mimeType"),x=g.getAttribute("codecs"),H=g.getAttribute("contentType")??E?.split("/")[0],q=g.getAttribute("profiles")?.split(",")??[],F=g.querySelectorAll("Representation"),G=g.querySelector("SegmentTemplate");if(H===Ie.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=g.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Ie.TEXT].push({id:V,lang:z,isAuto:ke,kind:Ie.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??E,z=T.getAttribute("codecs")??x??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=g.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,Be=pe?qi(pe):void 0,ot=T.getAttribute("id")??(b++).toString(10),oi=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,zt=`${ot}@${oi}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Ve=[...w,...q,...ye];let De;const vt=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(vt){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,dt]=Ae.split("-").map(ze=>parseInt(ze,10)),Ue={from:Pe,to:dt},it=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[_t,Et]=it?it.split("-").map(ze=>parseInt(ze,10)):[],st=it?{from:_t,to:Et}:void 0;De={type:Ze.BYTE_RANGE,url:we,initRange:Ue,indexRange:st}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),dt=Te.getAttribute("initialization")??"",Ue=Te.getAttribute("media"),it=parseInt(Te.getAttribute("startNumber")??"",10)??1,_t=Ji(dt,Ae);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Et=Te.querySelectorAll("SegmentTimeline S")??[],st=[];let ze=0;if(Et.length){let Mt=it,qe=0;for(const Ot of Et){const We=parseInt(Ot.getAttribute("d")??"",10),ve=parseInt(Ot.getAttribute("r")??"",10)||0,rt=parseInt(Ot.getAttribute("t")??"",10);qe=Number.isFinite(rt)?rt:qe;const He=We/Pe*1e3,ct=qe/Pe*1e3;for(let kt=0;kt<ve+1;kt++){const di=Ji(Ue,{...Ae,segmentNumber:Mt.toString(10),segmentTime:(qe+kt*We).toString(10)}),wi=(ct||0)+kt*He,qt=wi+He;Mt++,st.push({time:{from:wi,to:qt},url:di})}qe+=(ve+1)*We,ze+=(ve+1)*He}}else if(P(u)){const qe=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,Ot=Math.ceil(u/qe);let We=0;for(let ve=1;ve<Ot;ve++){const rt=Ji(Ue,{...Ae,segmentNumber:ve.toString(10),segmentTime:We.toString(10)});st.push({time:{from:We,to:We+qe},url:rt}),We+=qe}}De={type:Ze.TEMPLATE,baseUrl:we,initUrl:_t,totalSegmentsDurationMs:ze,segments:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ge={video:Ie.VIDEO,audio:Ie.AUDIO,text:Ie.TEXT}[te];Ge&&s[Ge].push({id:zt,kind:Ge,segmentReference:De,profiles:Ve,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:Be,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},ts=1e3,Ts=["timeupdate","progress","play","seeked","stalled","waiting"];var Xe;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Xe||(Xe={}));let Ka=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Xe.NONE);currentVideoRepresentation$=new m(void 0);currentVideoRepresentationInit$=new m(void 0);error$=new I;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);isLive$=new m(!1);liveDuration$=new m(0);liveAvailabilityStartTime$=new m(void 0);bufferLength$=new m(0);liveLoadBufferLength$=new m(0);forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ja({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Oe(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Xe.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Xe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=Xa(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Ie.TEXT);return this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){D(this.element),this.manifestUrlString=Oe(this.manifestUrlString,e,fe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=oe(this.destroyController.signal,async function*(e,t){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Xe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new bs(Ie.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new bs(Ie.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Yt(ts).subscribe(n=>{if(this.element?.paused){const o=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Oe(this.manifestUrlString,o+1e3,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...Ts.map(n=>M(this.element,n))).pipe(pr(ts),A(n=>this.element?Ye(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async o=>{D(this.element);const c=this.element.playbackRate,d=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),h=Ya*c,u=za*c,l=Ga*c;n=o>n?o:n;const p=d===0&&o<l,S=d!==0&&o<h+l&&o>=h,v=d!==0&&o<h;if(v||S){const b=n-(h+u),w=Math.trunc(d+b/c);let C;o?w>0?C=w:C=0:C=d,this.manifestUrlString=Oe(this.manifestUrlString,C,fe.DASH_CMAF_OFFSET_P)}(p||v||S)&&(await this.updateLive(),n=0)}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,xe({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Xe.REPRESENTATIOS_READY)}.bind(this));initBuffer(){D(this.element),this.state$.setState(Xe.RUNNING),this.subscription.add(O(...Ts.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ti(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Ie.VIDEO]:this.videoBufferManager,[Ie.AUDIO]:this.audioBufferManager,[Ie.TEXT]:null}[e]?.switchTo(t)}seek(e,t){D(this.element),D(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ti(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Xe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Yt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};class Za{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class en{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:s,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var tn=`#define GLSLIFY 1
|
|
38
|
+
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,sn=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
41
41
|
precision highp float;
|
|
42
42
|
#define GLSLIFY 1
|
|
43
43
|
#endif
|
|
44
44
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class js{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new en(this.params.fov,this.params.orientation),this.cameraRotationManager=new tn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(s,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(sn,this.gl.VERTEX_SHADER),i=this.createShader(rn,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,a=e-i,n=t-s,o=e+i,c=t-s,d=e+i,h=t+s,u=e-i,l=t+s;return[a,n,o,c,d,h,u,l]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let Js=class{scene3D;subscription=new se;videoState=new de(me.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new nt;droppedFramesManager=new ki;videoTracks$=new g([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Us;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Za({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=yt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:L.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ct(this.video,t.isLooped,s)),this.subscription.add(gt(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(wt(this.video,t.playbackRate,i.playbackRateState$,s)),a(Ti(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===me.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Je.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();w(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,D)=>D.bitrate-b.bitrate),p=Array.from(u.video).sort((b,D)=>D.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const D=Qa(b);D&&this.audioTracks.push({track:D,representation:b})}for(const b of p){const D=Wa(b);if(D){h.push({track:D,representation:b});const C=!this.params.tuning.isAudioDisabled&&ja(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const D=Ja(b);D&&this.textTracks.push({track:D,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const v=this.selectVideoRepresentation();w(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Je.REPRESENTATIOS_READY&&(this.videoState.setState(me.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Je.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Re.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Re.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=He(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=Gt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===j.Requested&&i?.to!==f.PAUSED&&e!==me.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==me.STOPPED&&(this.videoState.startTransitionTo(me.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(me.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case me.STOPPED:this.videoState.startTransitionTo(me.READY),this.prepare();return;case me.READY:t===f.PAUSED?(this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case me.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case me.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new js(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){Dt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}},an=class extends Js{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Ie;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Ie||(Ie={}));var ht;(function(r){r[r.ActiveLowLatency=0]="ActiveLowLatency",r[r.LiveWithTargetOffset=1]="LiveWithTargetOffset",r[r.LiveForwardBuffering=2]="LiveForwardBuffering",r[r.None=3]="None"})(ht||(ht={}));var Fi;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Fi||(Fi={}));var Ze;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Ze||(Ze={}));var Q;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(Q||(Q={}));var si;(function(r){r.MP4="mp4",r.WEBM="webm"})(si||(si={}));var Vi;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Vi||(Vi={}));var ge;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ge||(ge={}));let Xs=!1;try{Xs=Gi().browser===ns.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class nn{bufferFull$=new I;error$=new I;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Xs&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:L.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:L.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:N(t)}}}class et{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 Ks extends et{}class on extends et{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 dn extends et{parseChildrenBoxes(){return Bt(this.content)}}class cn extends et{parseChildrenBoxes(){return Bt(this.content)}}class un extends et{data;constructor(e){super(e),this.data=this.content}}class Pt extends et{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class hn extends Pt{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class ln extends et{parseChildrenBoxes(){return Bt(this.content)}}class fn extends et{parseChildrenBoxes(){return Bt(this.content)}}var Ut;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ut||(Ut={}));class pn extends Pt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ut.MONOSCOPIC;break;case 1:this.stereoMode=Ut.TOP_BOTTOM;break;case 2:this.stereoMode=Ut.LEFT_RIGHT;break;case 3:this.stereoMode=Ut.STEREO_CUSTOM;break;case 4:this.stereoMode=Ut.RIGHT_LEFT;break}this.cursor+=1}}class mn extends Pt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class gn extends Pt{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 Sn extends et{parseChildrenBoxes(){return Bt(this.content)}}class bn extends Pt{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 yn extends et{parseChildrenBoxes(){return Bt(this.content)}}class Tn extends et{parseChildrenBoxes(){return Bt(this.content)}}class vn extends Pt{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class En extends et{parseChildrenBoxes(){return Bt(this.content)}}class kn extends Pt{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class $n extends Pt{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class An extends Pt{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const wn={ftyp:on,moov:dn,moof:cn,mdat:un,sidx:hn,trak:ln,mdia:Sn,mfhd:vn,tkhd:bn,traf:En,tfhd:kn,tfdt:$n,trun:An,minf:yn,sv3d:fn,st3d:pn,prhd:mn,proj:Tn,equi:gn,unknown:Ks};class Dn{createBox(e,t){const i=wn[e];return i?new i(t):new Ks(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Qi.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Qi=new Dn;function mi(r,e){const t=new Uint8Array(r.buffer),i=e.split("").map(n=>n.charCodeAt(0));let s=r.byteOffset,a=[];for(;s<t.byteLength;){if(t[s]===i[a.length]?a.push(t[s]):a=[],a.length===4){const o=new DataView(r.buffer,s-7,4).getUint32(0);return s-7+o>r.buffer.byteLength?null:Qi.createBox(e,new DataView(r.buffer,s-7))}s++}return null}function is(r,e){const t=[];let i=r.byteOffset;for(;i<r.buffer.byteLength;){const s=mi(new DataView(r.buffer,i,r.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function Bt(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Qi.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Pn=new TextDecoder("ascii"),xn=r=>Pn.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",Ln=r=>{const e=Qi.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Q.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Rn=r=>{const e=is(r,"mdat"),t=is(r,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],a=i.source.byteOffset,o=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(r.buffer,a,o)},In=(r,e)=>{const t=is(r,"traf"),i=t[t.length-1].children.find(c=>c.type==="tfhd"),s=t[t.length-1].children.find(c=>c.type==="tfdt"),a=t[t.length-1].children.find(c=>c.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((c,d)=>c+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(s.baseMediaDecodeTime)+n)/e*1e3},Cn=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Vi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(mi(r,"sv3d")){e.is3dVideo=!0;const i=mi(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=mi(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=mi(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Bn={validateData:xn,parseInit:Cn,getIndexRange:()=>{},parseSegments:Ln,parseFeedableSegmentChunk:Rn,getSegmentEndTime:In};var k;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(k||(k={}));var _;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(_||(_={}));const vs={[k.EBML]:{type:_.Master},[k.EBMLVersion]:{type:_.UnsignedInteger},[k.EBMLReadVersion]:{type:_.UnsignedInteger},[k.EBMLMaxIDLength]:{type:_.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[k.DocType]:{type:_.String},[k.DocTypeVersion]:{type:_.UnsignedInteger},[k.DocTypeReadVersion]:{type:_.UnsignedInteger},[k.Void]:{type:_.Binary},[k.Segment]:{type:_.Master},[k.SeekHead]:{type:_.Master},[k.Seek]:{type:_.Master},[k.SeekID]:{type:_.Binary},[k.SeekPosition]:{type:_.UnsignedInteger},[k.Info]:{type:_.Master},[k.TimestampScale]:{type:_.UnsignedInteger},[k.Duration]:{type:_.Float},[k.Tracks]:{type:_.Master},[k.TrackEntry]:{type:_.Master},[k.Video]:{type:_.Master},[k.Projection]:{type:_.Master},[k.ProjectionType]:{type:_.UnsignedInteger},[k.ProjectionPrivate]:{type:_.Master},[k.Chapters]:{type:_.Master},[k.Cluster]:{type:_.Master},[k.Timestamp]:{type:_.UnsignedInteger},[k.SilentTracks]:{type:_.Master},[k.SilentTrackNumber]:{type:_.UnsignedInteger},[k.Position]:{type:_.UnsignedInteger},[k.PrevSize]:{type:_.UnsignedInteger},[k.SimpleBlock]:{type:_.Binary},[k.BlockGroup]:{type:_.Master},[k.EncryptedBlock]:{type:_.Binary},[k.Attachments]:{type:_.Master},[k.Tags]:{type:_.Master},[k.Cues]:{type:_.Master},[k.CuePoint]:{type:_.Master},[k.CueTime]:{type:_.UnsignedInteger},[k.CueTrackPositions]:{type:_.Master},[k.CueTrack]:{type:_.UnsignedInteger},[k.CueClusterPosition]:{type:_.UnsignedInteger},[k.CueRelativePosition]:{type:_.UnsignedInteger},[k.CueDuration]:{type:_.UnsignedInteger},[k.CueBlockNumber]:{type:_.UnsignedInteger},[k.CueCodecState]:{type:_.UnsignedInteger},[k.CueReference]:{type:_.Master},[k.CueRefTime]:{type:_.UnsignedInteger}},Zs=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ui(r,t),s=i in vs,a=s?vs[i].type:_.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Ui(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Ui=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},pt=(r,e)=>{switch(e){case _.SignedInteger:return r.getInt8(0);case _.UnsignedInteger:return Ui(r);case _.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(r);case _.UTF8:return new TextDecoder("utf-8").decode(r);case _.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case _.Master:return r;case _.Binary:return r;default:N(e)}},ri=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=Zs(i);if(!e(s))return;s.type===_.Master&&ri(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},_n=r=>{if(r.getUint32(0)!==k.EBML)return!1;let e,t,i;const s=Zs(r);return ri(s.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=pt(o,n):a===k.DocType?t=pt(o,n):a===k.DocTypeReadVersion&&(i=pt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},er=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],Mn=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],On=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ri(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===k.SeekID){const b=pt(S,p);d=Ui(b)}else l!==k.SeekPosition&&(d=void 0);return l===k.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===k.Info?a=!0:l===k.SeekHead?n=!0:l===k.TimestampScale?i=pt(S,p):l===k.Duration?s=pt(S,p):l===k.SeekPosition&&d===k.Cues?c=pt(S,p):l===k.Tracks?ri(S,({tag:b,type:D,value:C})=>b===k.ProjectionType?(h=pt(C,D)===1,!1):!0):a&&n&&er.includes(l)&&(o=!0),!o}),w(e,"Failed to parse webm Segment start"),w(t,"Failed to parse webm Segment end"),w(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:u,projectionType:Vi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Nn=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Fn=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ri(r,({tag:o,type:c,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&s(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=pt(d,c));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=pt(d,c));break;default:t&&er.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:Q.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Vn=r=>{let e=0,t=!1;try{ri(r,i=>i.tag===k.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Mn.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Un={validateData:_n,parseInit:On,getIndexRange:Nn,parseSegments:Fn,parseFeedableSegmentChunk:Vn},Es=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},jt=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},Hn=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=Es(l);else if(p){const m=Es(p);P(m)&&(u=m)}else v&&(u=parseInt(v,10));let b=0;const D=a.getAttribute("profiles")?.split(",")??[],C=D.includes(Fi.WEBM_AS_IN_FFMPEG)||D.includes(Fi.WEBM_AS_IN_SPEC)?si.WEBM:si.MP4;for(const m of o){const $=m.getAttribute("mimeType"),x=m.getAttribute("codecs"),H=m.getAttribute("contentType")??$?.split("/")[0],q=m.getAttribute("profiles")?.split(",")??[],F=m.querySelectorAll("Representation"),G=m.querySelector("SegmentTemplate");if(H===Ie.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=m.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Ie.TEXT].push({id:V,lang:z,isAuto:ke,kind:Ie.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??$,z=T.getAttribute("codecs")??x??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=m.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,Ce=pe?qi(pe):void 0,ot=T.getAttribute("id")??(b++).toString(10),oi=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,zt=`${ot}@${oi}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Fe=[...D,...q,...ye];let De;const vt=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(vt){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,dt]=Ae.split("-").map(Ge=>parseInt(Ge,10)),Ve={from:Pe,to:dt},tt=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[_t,Et]=tt?tt.split("-").map(Ge=>parseInt(Ge,10)):[],it=tt?{from:_t,to:Et}:void 0;De={type:Ze.BYTE_RANGE,url:we,initRange:Ve,indexRange:it}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),dt=Te.getAttribute("initialization")??"",Ve=Te.getAttribute("media"),tt=parseInt(Te.getAttribute("startNumber")??"",10)??1,_t=jt(dt,Ae);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");const Et=Te.querySelectorAll("SegmentTimeline S")??[],it=[];let Ge=0,Mt="",ze=0;if(Et.length){let qe=tt,ve=0;for(const st of Et){const Ue=parseInt(st.getAttribute("d")??"",10),ct=parseInt(st.getAttribute("r")??"",10)||0,kt=parseInt(st.getAttribute("t")??"",10);ve=Number.isFinite(kt)?kt:ve;const di=Ue/Pe*1e3,Ai=ve/Pe*1e3;for(let qt=0;qt<ct+1;qt++){const or=jt(Ve,{...Ae,segmentNumber:qe.toString(10),segmentTime:(ve+qt*Ue).toString(10)}),hs=(Ai??0)+qt*di,dr=hs+di;qe++,it.push({time:{from:hs,to:dr},url:or})}ve+=(ct+1)*Ue,Ge+=(ct+1)*di}ze=ve/Pe*1e3,Mt=jt(Ve,{...Ae,segmentNumber:qe.toString(10),segmentTime:ve.toString(10)})}else if(P(u)){const ve=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,st=Math.ceil(u/ve);let Ue=0;for(let ct=1;ct<st;ct++){const kt=jt(Ve,{...Ae,segmentNumber:ct.toString(10),segmentTime:Ue.toString(10)});it.push({time:{from:Ue,to:Ue+ve},url:kt}),Ue+=ve}ze=Ue,Mt=jt(Ve,{...Ae,segmentNumber:st.toString(10),segmentTime:Ue.toString(10)})}const Ot={time:{from:ze,to:1/0},url:Mt};De={type:Ze.TEMPLATE,baseUrl:we,segmentTemplateUrl:Ve,initUrl:_t,totalSegmentsDurationMs:Ge,segments:it,nextSegmentBeyondManifest:Ot,timescale:Pe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ye={video:Ie.VIDEO,audio:Ie.AUDIO,text:Ie.TEXT}[te];Ye&&s[Ye].push({id:zt,kind:Ye,segmentReference:De,profiles:Fe,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:Ce,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},Yn=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?ai(a):void 0)??It({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},Gn=({id:r,bitrate:e})=>({id:r,bitrate:e}),zn=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},qn=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),ks=r=>"size"in r,Wt=r=>r.type===Ze.TEMPLATE,ss=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);class $s{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);playingRepresentationInit$=new g(void 0);error$=new I;gaps=[];subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new AbortController;destroyAbortController=new AbortController;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;constructor(e,t,i,s,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:c,compatibilityMode:d=!1,manifest:h}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=c,this.isLive=!!h?.dynamic,this.container=i,i){case si.MP4:this.containerParser=Bn;break;case si.WEBM:this.containerParser=Un;break;default:N(i)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);w(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new nn(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);w(i,"No init buffer for starting representation"),w(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);w(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),w(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();P(a)&&(this.isLive||(i.forEach(n=>n.status=Q.NONE),this.pruneBuffer(a,1/0,!0)),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(w(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=He(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Oi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=He(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===Q.FED&&!o.length&&He(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=i.at(-1);c&&c.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+s}),i=a.time.to;P(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let a=0,n=t.length-1;do s.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d||!Wt(d.segmentReference))return;const h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);w(i);const s=this.segments.get(t);w(s,"No segments for starting representation");const a=this.initData.get(t);if(w(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!Wt(t.segmentReference))return;const i=t.segmentReference.segments.map(o=>({...o,status:Q.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.floor(a)>=Math.floor(o.time.from)&&Math.floor(a)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!Wt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),a=jt(i.segmentTemplateUrl,{segmentTime:s}),n=this.segments.get(t.id)??[],o=n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||n.push({status:Q.NONE,time:{from:e.segment.time.to,to:1/0},url:a})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,D=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+D||p<=i+D;return(u===Q.NONE||u===Q.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!ti(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==Ze.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===Q.NONE||l.status===Q.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){t.segmentReference.type===Ze.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Q.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:a,url:n,signal:o,onProgress:c,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await oe(o,async function*(){const h=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,h))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:c,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const u=new DataView(h);if(this.isActiveLowLatency()){const l=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(u,l)}c&&s.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(u,o),s.segment.status=Q.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!ss(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const c of e)c.status=Q.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await oe(n,async function*(){const c=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:s,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(c){if(!ss(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}}prepareByteRangeFetchSegmentParams(e,t){if(Wt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:s,signal:a,onProgress:(c,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const s=i.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,u)=>{if(!a.aborted)try{const l=this.onSomeTemplateDataLoaded({dataView:h,loaded:u,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:s,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&P(i)&&(t=He(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:c}=o;if(o.representationId===t){if(a.aborted){s();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(d);h?.byteLength&&(c.status=Q.PARTIALLY_FED,o.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),o.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const c=o.segmentReference.type,d=e.byteLength;for(const h of this.activeSegments){const{segment:u}=h,l=c===Ze.BYTE_RANGE,p=l?u.byte.to-u.byte.from+1:d;if(h.representationId!==t||!(!l||u.byte.from>=i&&u.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const v=l?u.byte.from-i:0,b=l?u.byte.to-i:e.byteLength,D=v<s,C=b<=s;if(u.status===Q.DOWNLOADING&&D&&C){u.status=Q.DOWNLOADED;const m=new DataView(e.buffer,e.byteOffset+v,p);this.sourceBufferTaskQueue.append(m,a).then($=>$&&!a.aborted?this.onSegmentFullyAppended(h,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&D&&(h.loadedBytes=Math.min(p,s-v),h.loadedBytes>h.feedingBytes)){const m=new DataView(e.buffer,e.byteOffset+v+h.feedingBytes,h.loadedBytes-h.feedingBytes),$=h.loadedBytes===p?m:this.containerParser.parseFeedableSegmentChunk(m);$?.byteLength&&(u.status=Q.PARTIALLY_FED,h.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(x=>{if(a.aborted)n();else if(x)h.fedBytes+=$.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Q.FED,ks(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===Q.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=Q.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:c,dataView:d,segments:h}=o,u=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,u);let l=h;this.isLive&&Wt(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h=ks(d)?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===Q.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===Q.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===Q.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===Q.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==Q.FED&&a!==Q.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=Q.PARTIALLY_EJECTED:s.status=Q.NONE)}}}var Xt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Xt||(Xt={}));class Wn{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new AbortController;subscription=new se;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Rt(t));const i=yield fetch(t,{signal:this.abortAllController.signal}).catch(hi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Xt.HEADER:Xt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let d=e;const h=new Headers;if(i)switch(t){case Xt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Xt.PARAM:{const F=new URL(d,location.href);F.searchParams.append("bytes",`${i.from}-${i.to}`),d=F.toString();break}default:N(t)}this.requestQuic&&(d=Rt(d));let u=this.abortAllController.signal,l;if(n){const F=new AbortController;if(l=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{F.abort()}catch(G){hi(G)}}),this.abortAllController.signal.aborted||n.aborted)try{F.abort()}catch(G){hi(G)}u=F.signal}const p=ne(),S=yield fetch(d,{priority:a,headers:h,signal:u}).catch(hi),v=ne();if(!S)return l?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-p),!S.ok||!S.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));if(this.onHeadersReceived(S.headers),!s&&!o)return l?.unsubscribe(),S.arrayBuffer();const[b,D]=S.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(D,c);let m=0,$=new Uint8Array(0),x=!1;const H=F=>{l?.unsubscribe(),x=!0,hi(F)},q=oe(u,async function*({done:F,value:G}){if(m===0&&this.lastRequestFirstBytes$.next(ne()-p),u.aborted){l?.unsubscribe();return}if(!F&&G){const T=new Uint8Array($.length+G.length);T.set($),T.set(G,$.length),$=T,m+=G.byteLength,s?.(new DataView($.buffer),m),yield C?.read().then(q,H)}}.bind(this));return yield C?.read().then(q,H),l?.unsubscribe(),x?null:$.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ze.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ze.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ze.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const D=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!D)return null;v=new DataView(D)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==Ze.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(n=>({...n,status:Q.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const hi=r=>{if(!ss(r))throw r},rs=1e3,Hi=(r,e,t)=>t*e+(1-t)*r,tr=(r,e)=>r.reduce((t,i)=>t+i,0)/e,Qn=(r,e,t,i)=>{let s=0,a=t;const n=tr(r,e),o=e<i?e:i;for(let c=0;c<o;c++)r[a]>n?s++:s--,a=(r.length+a-1)%r.length;return Math.abs(s)===o};class us{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new g(e.initial),this.debounced$=new g(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new lt(`raw_${t}`),this.smoothedSeries$=new lt(`smoothed_${t}`),this.reportedSeries$=new lt(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(Y(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class jn extends us{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Hi(this.slow,e,this.params.emaAlphaSlow),this.fast=Hi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Jn extends us{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=tr(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Hi(this.emaSmoothed,e,this.params.emaAlpha);const i=Qn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Xn extends us{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?Hi(this.smoothed,e,this.params.emaAlpha):e}}class as{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new jn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Jn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Xn({initial:e,label:"liveEdgeDelay",...t})}}const Kn=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)},As=["timeupdate","progress","play","seeked","stalled","waiting"];var Xe;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Xe||(Xe={}));let Zn=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Xe.NONE);currentVideoRepresentation$=new g(void 0);currentVideoRepresentationInit$=new g(void 0);error$=new I;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);isLive$=new g(!1);liveDuration$=new g(0);liveAvailabilityStartTime$=new g(void 0);bufferLength$=new g(0);liveLoadBufferLength$=new g(0);livePositionFromPlayer$=new g(0);liveEstimatedDelay;liveWaitingEventCallback;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Wn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=as.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.liveWaitingEventCallback=yr(this._liveWaitingEventCallback,this.tuning.dashCmafLive.maxWaitingDuration)}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Me(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Xe.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Xe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=Hn(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Ie.TEXT);return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){w(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.liveLastSeekOffset=e,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Me(this.manifestUrlString,e,fe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=oe(this.destroyController.signal,async function*(e,t){w(this.manifest),w(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Xe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new $s(Ie.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new $s(Ie.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Yt(rs).subscribe(n=>{if(this.element?.paused){const o=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Me(this.manifestUrlString,o+rs,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...As.map(n=>M(this.element,n))).pipe(A(n=>this.element?He(this.element.buffered,this.element.currentTime*1e3):0),le(),K(n=>!!n)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(K(o=>this.isActiveLowLatency&&!!o)).subscribe(o=>this.liveEstimatedDelay.next(o))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(o=>{if(!this.isActiveLowLatency)return;const c=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,d=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=o-c;let l=1+Math.sign(u)*h;Math.abs(u)<d?l=1:Math.abs(u)>d*2&&(l=1+Math.sign(u)*h*2),Kn(this.element,l)})),this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(xe({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:o,bufferLength:c})=>{if(w(this.element),this.liveWaitingEventCallback.cancel(),this.isUpdatingLive)return;const d=this.element.playbackRate,h=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,l=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*d),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*d,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*d,v=this.isActiveLowLatency?c:o;let b=ht.None;if(this.isActiveLowLatency?b=ht.ActiveLowLatency:v<l+S&&v>=l?b=ht.LiveWithTargetOffset:h!==0&&v<l&&(b=ht.LiveForwardBuffering),isFinite(o)&&(n=o>n?o:n),b===ht.LiveForwardBuffering||b===ht.LiveWithTargetOffset){const D=n-(l+p),C=Math.trunc(h+D/d);let m;o?C>0?m=C:m=0:m=h,this.manifestUrlString=Me(this.manifestUrlString,m,fe.DASH_CMAF_OFFSET_P)}b!==ht.None&&b!==ht.ActiveLowLatency&&(n=0,this.updateLive())}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,xe({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Xe.REPRESENTATIOS_READY)}.bind(this));initBuffer(){w(this.element),this.state$.setState(Xe.RUNNING),this.subscription.add(O(...As.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ti(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.isLive$.getValue()&&this.liveWaitingEventCallback()})),this.tick()}async switchRepresentation(e,t){return{[Ie.VIDEO]:this.videoBufferManager,[Ie.AUDIO]:this.audioBufferManager,[Ie.TEXT]:null}[e]?.switchTo(t)}seek(e,t){w(this.element),w(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ti(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Xe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}async _liveWaitingEventCallback(){try{await this.seekLive(this.liveLastSeekOffset)}catch(e){this.error$.next({id:"LiveWaitingEventCallback",category:L.WTF,message:"Error in seeking live in live waiting event callback",thrown:e})}}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Yt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class ir{scene3D;subscription=new se;videoState=new de(ge.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new nt;droppedFramesManager=new ki;videoTracks$=new g([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Us;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Zn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=yt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:L.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ct(this.video,t.isLooped,s)),this.subscription.add(gt(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(wt(this.video,t.playbackRate,i.playbackRateState$,s)),a(Ti(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Xe.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();w(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,D)=>D.bitrate-b.bitrate),p=Array.from(u.video).sort((b,D)=>D.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const D=Gn(b);D&&this.audioTracks.push({track:D,representation:b})}for(const b of p){const D=Yn(b);if(D){h.push({track:D,representation:b});const C=!this.params.tuning.isAudioDisabled&&zn(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const D=qn(b);D&&this.textTracks.push({track:D,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const v=this.selectVideoRepresentation();w(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Xe.REPRESENTATIOS_READY&&(this.videoState.setState(ge.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Xe.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Ie.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Ie.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=He(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=Gt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===j.Requested&&i?.to!==f.PAUSED&&e!==ge.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ge.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case ge.STOPPED:this.videoState.startTransitionTo(ge.READY),this.prepare();return;case ge.READY:t===f.PAUSED?(this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case ge.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ge.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new js(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){Dt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}}class eo extends ir{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let to=class extends Js{constructor(e){super(e),this.liveOffset=new Ei}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(xe({interval:Yt(ts),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===me.PLAYING){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(xe({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===f.PAUSED&&i===me.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}};class io extends ir{constructor(e){super(e),this.liveOffset=new Ei}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(xe({interval:Yt(rs),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ge.PLAYING&&!this.player.isActiveLowLatency){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(xe({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===f.PAUSED&&i===ge.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const ut={};var ie;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ie||(ie={}));const li=(r,e)=>new zi(t=>{const i=(s,a)=>t.next(a);return r.on(e,i),()=>r.off(e,i)});class so{subscription=new se;videoState=new de(ie.INITIALIZING);video;params;hls;textTracksManager=new nt;trackLevels=new Map;constructor(e){this.video=St(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),bt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:L.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(ut.Hls=s.default,ut.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){w(ut.Hls,"hls.js not loaded"),this.hls=new ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ie.STOPPED)}subscribe(){w(ut.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:L.WTF,message:"HlsJsProvider internal logic error",thrown:d})},s=yt(this.video),a=(d,h)=>this.subscription.add(d.subscribe(h,i));a(s.timeUpdate$,t.position$),a(s.durationChange$,t.duration$),a(s.ended$,t.endedEvent$),a(s.looped$,t.loopedEvent$),a(s.error$,t.error$),a(s.isBuffering$,t.isBuffering$),a(s.currentBuffer$,t.currentBuffer$),a(s.loadStart$,t.firstBytesEvent$),a(s.playing$,t.firstFrameEvent$),a(s.canplay$,t.canplay$),a(s.seeked$,t.seekedEvent$),a(s.inPiP$,t.inPiP$),a(s.inFullscreen$,t.inFullscreen$),this.subscription.add(Ct(this.video,e.isLooped,i)),this.subscription.add(gt(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(wt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(li(this.hls,ut.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:L.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),R(e.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),R(e.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),a(li(this.hls,ut.Events.MANIFEST_PARSED).pipe(A(({levels:d})=>d.reduce((h,u)=>{const l=u.name||u.height.toString(10),{width:p,height:S}=u,v=ai(u.attrs.QUALITY??"")??It({width:p,height:S});if(!v)return h;const b=u.attrs["FRAME-RATE"]?parseFloat(u.attrs["FRAME-RATE"]):void 0,D={id:l.toString(),quality:v,bitrate:u.bitrate/1e3,size:{width:p,height:S},fps:b};return this.trackLevels.set(l,{track:D,level:u}),h.push(D),h},[]))),t.availableVideoTracks$),a(li(this.hls,ut.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const h=[];for(const u of d.subtitleTracks){const l=u.name,p=u.attrs.URI||"",S=u.lang,v="internal";h.push({id:l,url:p,language:S,type:v})}e.internalTextTracks.startTransitionTo(h)}}),a(li(this.hls,ut.Events.LEVEL_LOADING).pipe(A(({url:d})=>Ne(d))),t.hostname$),this.subscription.add(at(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>Array.from(this.trackLevels.values()).find(({level:h})=>h===d)?.track,o=li(this.hls,ut.Events.LEVEL_SWITCHED).pipe(A(({level:d})=>n(this.hls.levels[d])));o.pipe(K(P)).subscribe(t.currentVideoTrack$,i),this.subscription.add(at(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{if(Y(d))return;const h=this.trackLevels.get(d.id)?.level;if(!h)return;const u=this.hls.levels.indexOf(h),l=this.hls.currentLevel,p=this.hls.levels[l];!p||h.bitrate>p.bitrate?this.hls.nextLevel=u:(this.hls.loadLevel=u,this.hls.loadLevel=u)},{changed$:o,onError:i})),a(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(c.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==ie.INITIALIZING)switch(i?.to!==f.PAUSED&&s.state===j.Requested&&this.seek(s.position),t){case f.STOPPED:switch(e){case ie.STOPPED:break;case ie.READY:case ie.PLAYING:case ie.PAUSED:this.stop();break;default:N(e)}break;case f.READY:switch(e){case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PLAYING:case ie.PAUSED:break;default:N(e)}break;case f.PLAYING:switch(e){case ie.PLAYING:break;case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PAUSED:this.playIfAllowed();break;default:N(e)}break;case f.PAUSED:switch(e){case ie.PAUSED:break;case ie.STOPPED:this.prepare();break;case ie.READY:this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case ie.PLAYING:this.pause();break;default:N(e)}break;default:N(t)}};prepare(){this.videoState.startTransitionTo(ie.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ie.PLAYING),await Dt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:t}))||(this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ie.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(ie.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}}const ws="X-Playback-Duration";var Ds=async r=>{const e=await fetch(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(ws)?parseInt(e.headers.get(ws),10):void 0};const ro=r=>{let e=null;if(r.QUALITY&&(e=ai(r.QUALITY)),!e&&r.RESOLUTION){const[t,i]=r.RESOLUTION.split("x").map(s=>parseInt(s,10));e=It({width:t,height:i})}return e??null},sr=async(r,e=r)=>{const s=(await(await fetch(r)).text()).split(`
|
|
46
|
-
`),a=[],n=[];for(let o=0;o<s.length;o++){const c=s[o],d=c.match(/^#EXT-X-STREAM-INF:(.+)/),h=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!h)){if(d){const u=Object.fromEntries(d[1].split(",").map(C=>C.split("="))),l=u.QUALITY??`stream-${u.BANDWIDTH}`,p=ro(u);let S;u.BANDWIDTH&&(S=parseInt(u.BANDWIDTH,10)/1e3||void 0),!S&&u["AVERAGE-BANDWIDTH"]&&(S=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let b;if(u.RESOLUTION){const[C,m]=u.RESOLUTION.split("x").map($=>parseInt($,10));C&&m&&(b={width:C,height:m})}const D=new URL(s[++o],e).toString();p&&a.push({id:l,quality:p,url:D,bandwidth:S,size:b,fps:v})}if(h){const u=Object.fromEntries(h[1].split(",").map(v=>v.split("=")).map(([v,b])=>[v,b.replace(/^"|"$/g,"")])),l=u.URI?.replace(/playlist$/,"subtitles.vtt"),p=u.LANGUAGE,S=u.NAME;l&&p&&n.push({type:"internal",id:p,label:S,language:p,url:l,isAuto:!1})}}}return{qualityManifests:a,textTracks:n}};var ce;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(ce||(ce={}));class ao{subscription=new se;videoState=new de(ce.STOPPED);video;params;textTracksManager=new nt;masterManifest;manifests$=new g([]);maxSeekBackTime$;liveOffset=new Ei;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:je.INVARIANT,url:this.params.source.url},sr(Me(this.params.source.url),this.params.source.url).then(({qualityManifests:t})=>{this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.maxSeekBackTime$=new g(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:L.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=yt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.ended$,e.endedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(gt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(wt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(le(),A(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Ne(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===ce.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===j.Requested&&this.seek(o.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(xe({startTime:this.manifestStartTime$.pipe(K(P)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),i)),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Oe(["init"])).pipe(Qe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(Y(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URLSearchParams(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:o,min:c}=t?.to??i??{};for(const[d,h]of[[o,"mq"],[c,"lq"]]){const u=String(parseFloat(d||""));h&&u&&s.set(h,u)}}const a=this.params.format===y.HLS_LIVE_CMAF?fe.DASH_CMAF_OFFSET_P:fe.OFFSET_P,n=Me(s.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",n),this.video.load(),Ds(n).then(o=>{if(!Y(o))this.maxSeekBackTime$.next(o);else{const c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Y(c)||!isFinite(c))try{fetch(n).then(d=>d.text()).then(d=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(h){const u=new URL(h,n).toString();Ds(u).then(l=>{Y(l)||this.maxSeekBackTime$.next(l)})}})}catch{}}})}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(ce.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==f.PAUSED&&d.state===j.Requested){this.videoState.startTransitionTo(ce.READY),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case ce.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ce.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(ce.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else s?.to===f.PAUSED&&(R(this.params.desiredState.playbackState,f.PAUSED),this.liveOffset.pause());return;case ce.CHANGING_MANIFEST:break;default:return N(t)}}}var he;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(he||(he={}));class no{subscription=new se;videoState=new de(he.STOPPED);video;params;textTracksManager=new nt;masterManifest;manifests$=new g([]);constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:je.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),sr(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:L.WTF,message:"HlsProvider internal logic error",thrown:o})},s=yt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c));if(a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(wt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===he.READY&&this.videoState.setState(he.READY),this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Ne(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===he.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===j.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i)),!pr()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(O(M(o,"addtrack"),M(o,"removetrack"),M(o,"change"),Oe(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},i))}const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Oe(["init"])).pipe(Qe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(Y(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URLSearchParams(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:a,min:n}=t?.to??i??{};for(const[o,c]of[[a,"mq"],[n,"lq"]]){const d=String(parseFloat(o||""));c&&d&&s.set(c,d)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(he.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===he.STOPPED){this.videoState.startTransitionTo(he.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(he.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:u}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:u*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&d.state===j.Requested&&this.seek(d.position),t){case he.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed());return;case he.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case he.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;case he.CHANGING_MANIFEST:break;default:return N(t)}}}var Se;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Se||(Se={}));class oo{subscription=new se;videoState=new de(Se.STOPPED);video;trackUrls={};params;textTracksManager=new nt;constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const a=s.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},s=yt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(wt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Se.READY&&this.videoState.setState(Se.READY);const o=this.params.desiredState.videoTrack.getTransition();o&&P(o.to)&&(this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track)),this.videoState.getState()===Se.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;w(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];w(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Rt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ne(t))}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===f.STOPPED){e!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Se.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!==Se.READY&&!n){this.handleQualityLimitTransition(a.to.max);return}if(e===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){const{currentTime:c}=this.video;this.prepare(),o.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==f.PAUSED&&o.state===j.Requested&&this.seek(o.position),e){case Se.READY:t===f.READY?R(this.params.desiredState.playbackState,f.READY):t===f.PAUSED?(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Se.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(o=>!Ht(o.track.quality)&&Ns(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[a??"0"]?.track;if(s&&n&&Ki(n.quality,s.quality)&&(t=s),!t){const o=Object.values(this.trackUrls).filter(d=>!Ht(d.track.quality)&&Kt(d.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(a=>a.track);t=Gt(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}}const Ps=["stun:videostun.mycdn.me:80"],co=1e3,uo=3,Xi=()=>null;class ho{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Xi;externalStopCallback=Xi;externalErrorCallback=Xi;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Ps}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:L.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),co)}normalizeOptions(e={}){const t={stunServerList:Ps,maxRetryNumber:uo,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ue;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ue||(ue={}));class lo{subscription;params;log;video;videoState=new de(ue.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=St(e.container),this.liveStreamClient=new ho(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(this.videoState.stateChangeStarted$.pipe(A(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=yt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(s.timeUpdate$,e.liveTime$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ue.READY&&this.videoState.setState(ue.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(gt(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ue.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(f.STOPPED);break;case ue.READY:break;case ue.PAUSED:t.playbackState.setState(f.PAUSED);break;case ue.PLAYING:t.playbackState.setState(f.PLAYING);break;default:return N(n.to)}},i)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Qe(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:je.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,f.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ue.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:L.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===f.STOPPED){e!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ue.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===ue.STOPPED){this.videoState.startTransitionTo(ue.READY),this.prepare();return}if(a){this.prepare();return}switch(e){case ue.READY:t===f.PAUSED?(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed());return;case ue.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ue.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}class xs{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const rr=Gi().device===mr.Android,Yi=document.createElement("video"),fo='video/mp4; codecs="avc1.42000a,mp4a.40.2"',po='video/mp4; codecs="hev1.1.6.L93.B0"',ar='video/webm; codecs="vp09.00.10.08"',nr='video/webm; codecs="av01.0.00M.08"',mo='audio/mp4; codecs="mp4a.40.2"',go='audio/webm; codecs="opus"',rt={mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(Yi.canPlayType?.("application/x-mpegurl")||Yi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},We={mp4:!!Yi.canPlayType?.("video/mp4"),webm:!!Yi.canPlayType?.("video/webm"),cmaf:!0},mt={h264:!!window.MediaSource?.isTypeSupported?.(fo),h265:!!window.MediaSource?.isTypeSupported?.(po),vp9:!!window.MediaSource?.isTypeSupported?.(ar),av1:!!window.MediaSource?.isTypeSupported?.(nr),aac:!!window.MediaSource?.isTypeSupported?.(mo),opus:!!window.MediaSource?.isTypeSupported?.(go)},Qt=(mt.h264||mt.h265)&&mt.aac;var Lt;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Lt||(Lt={}));var At;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(At||(At={}));let Nt;const So=async()=>{if(!window.navigator.mediaCapabilities)return;const r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:nr}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:ar}})]);Nt={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{So()}catch(r){console.error(r)}const vi=rt.hls&&We.mp4,bo=()=>Object.keys(mt).filter(r=>mt[r]),yo=(r,e=!1)=>r.filter(t=>{switch(t){case y.DASH:return rt.mse&&We.mp4&&Qt;case y.DASH_SEP:return rt.mse&&We.mp4&&Qt;case y.DASH_WEBM:return rt.mse&&We.webm&&mt.vp9&&mt.opus;case y.DASH_WEBM_AV1:return rt.mse&&We.webm&&mt.av1&&mt.opus;case y.DASH_LIVE:return rt.mse&&We.mp4&&Qt;case y.DASH_LIVE_CMAF:return rt.mse&&We.mp4&&Qt&&We.cmaf;case y.DASH_ONDEMAND:return rt.mse&&We.mp4&&Qt;case y.HLS:case y.HLS_ONDEMAND:return vi||e&&rt.mse&&We.mp4&&Qt;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return vi;case y.MPEG:return We.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return rt.webrtc&&rt.ws&&mt.h264&&(We.mp4||We.webm);default:return N(t)}}),fi=r=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(r){case Lt.VP9:return[e,t];case Lt.AV1:return[t,e];case Lt.NONE:return[];case Lt.SMOOTH:return Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case Lt.POWER_EFFICIENT:return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:N(r)}return[e,t]},To=({webmCodec:r,androidPreferredFormat:e})=>{if(rr)switch(e){case At.MPEG:return[y.MPEG,...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case At.HLS:return[y.HLS,y.HLS_ONDEMAND,...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case At.DASH:return[...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return vi?[...fi(r),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},vo=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],s=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...s],n=[...s,...i];let o;if(rr)switch(r){case At.DASH:{o=a;break}case At.HLS:case At.MPEG:{o=n;break}}else vi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Ls=r=>r?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var Eo=r=>new zi(e=>{const t=new se,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(A(({from:d,to:h})=>`${d}-${h}`)),s=r.desiredPlaybackState$.stateChangeEnded$,a=r.providerChanged$.pipe(A(({type:d})=>d!==void 0)),n=new I;let o=0,c="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),r.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(c),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const ko={cacheDuration:12e4},$o={chunkDuration:5e3,maxParallelRequests:5};class Ao{current$=new g({type:void 0});providerError$=new I;noAvailableProvidersError$=new I;providerOutput={position$:new g(0),duration$:new g(1/0),volume$:new g({muted:!1,volume:1}),currentVideoTrack$:new g(void 0),availableVideoTracks$:new g([]),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),autoVideoTrackLimitingAvailable$:new g(!1),autoVideoTrackLimits$:new g(void 0),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new I,warning$:new I,willSeekEvent$:new I,seekedEvent$:new I,loopedEvent$:new I,endedEvent$:new I,firstBytesEvent$:new I,firstFrameEvent$:new I,canplay$:new I,isLive$:new g(void 0),isLowLatency$:new g(!1),canChangePlaybackSpeed$:new g(!0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),inPiP$:new g(!1),inFullscreen$:new g(!1),element$:new g(void 0),availableSources$:new g(void 0),is3DVideo$:new g(!1)};subscription=new se;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=yo([...vo(this.params.tuning),...To(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>P(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let a=[];i?a=[i]:s.length?a=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new xs(a);const n=[...Ls(!0),...Ls(!1)];this.chromecastFormatsIterator=new xs(n.filter(o=>P(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(Y(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:L.WTF,message:"Failed to create provider",thrown:s})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),s=i.state!==j.None;if(this.params.desiredState.seekState.setState({state:j.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Be.SCREEN:return this.createScreenProvider(t);case Be.CHROMECAST:return this.createChromecastProvider(t);default:return N(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return w(o),new la({...n,source:o,config:ko})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return w(o),this.params.tuning.useDashJs?new ps({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new eo({...n,source:o}):new an({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return w(o),this.params.tuning.useDashJsCMAF?new ps({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new io({...n,source:o}):new to({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return w(o),vi||!this.params.tuning.useHlsJs?new no({...n,source:o}):new so({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return w(o),new ao({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return w(o),new oo({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return w(o),new oa({...n,source:o,config:{...$o,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return w(o),new lo({container:i,source:o,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return w(o),new Pr({connection:o,meta:a,container:i,source:t,format:e,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Be.CHROMECAST:Be.SCREEN}chooseFormat(e){switch(e){case Be.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Be.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return N(e)}}skipFormat(e){switch(e){case Be.SCREEN:return this.screenFormatsIterator.next();case Be.CHROMECAST:return this.chromecastFormatsIterator.next();default:return N(e)}}handleNoFormatsError(e){switch(e){case Be.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Be.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return N(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const a=new URL(s);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([s,a])=>[s,i(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,i=0;return e.add(O(this.providerOutput.error$,Eo({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(A(s=>({id:`ProviderHangup:${s}`,category:L.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(K(({to:a})=>a===f.PLAYING),be()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const a=this.current$.getValue().destination;if(a===Be.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Be.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===L.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(a??Be.SCREEN)}})),e}}const wo=5e3,Rs="one_video_throughput",Is="one_video_rtt",Si=window.navigator.connection,Cs=()=>{const r=Si?.downlink;if(P(r)&&r!==10)return r*1e3},Bs=()=>{const r=Si?.rtt;if(P(r)&&r!==3e3)return r},_s=(r,e,t)=>{const i=t*8,s=i/r;return i/(s+e)};class bi{throughput;rtt;subscription=new se;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=bi.load(Rs)||(e.useBrowserEstimation?Cs():void 0)||wo,i=bi.load(Is)??(e.useBrowserEstimation?Bs():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(i),this.rttAdjustedThroughput$=new g(_s(t,i,e.rttPenaltyRequestSize)),this.throughput=as.getSmoothedValue(t,-1,e),this.rtt=as.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=Cs();n&&this.throughput.next(n);const o=Bs();P(o)&&this.rtt.next(o)};Si&&"onchange"in Si&&this.subscription.add(M(Si,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{ji.set(Rs,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{ji.set(Is,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(xe({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(A(({throughput:s,rtt:a})=>_s(s,a,e.rttPenaltyRequestSize)),K(s=>{const a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ne();const s=new se;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(M(e,"progress").pipe(be()).subscribe(a=>{t=a.loaded,i=ne()}));break;case 1:case 0:s.add(M(e,"loadstart").subscribe(()=>{t=0,i=ne()}));break}s.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),c=n-t,d=o-i;this.addRawSpeed(c,d,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,a=ne(),n=0,o=ne();const c=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},d=async({done:h,value:u})=>{if(h)!t&&this.addRawSpeed(s,ne()-a,1),this.concurrentDownloads.delete(e);else if(u){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=u.byteLength;else{const p=o-a;p&&this.addRawSpeed(n,p,1,t),n=u.byteLength,a=ne()}o=ne()}else s+=u.byteLength,n+=u.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await i?.read().then(d,c)}};this.concurrentDownloads.add(e),i?.read().then(d,c)}addRawSpeed(e,t,i=1,s=!1){if(bi.sanityCheck(e,t,s)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=ji.get(e);if(P(t))return parseInt(t,10)??void 0}}const Ms={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:je.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,maxWaitingDuration:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Lt.VP9,androidPreferredFormat:At.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Do=r=>({...gr(r,Ms),configName:[...r.configName??[],...Ms.configName]});var Os=({seekState:r,position$:e})=>O(r.stateChangeEnded$.pipe(A(({to:t})=>t.state===j.None?void 0:(t.position??NaN)/1e3),K(P)),e.pipe(K(()=>r.getState().state===j.None))),Po=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return w(e,`Wrong container or containerId {${r.container}}`),e};const xo=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(K(s=>s.length>0),be()).subscribe(s=>{s.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};class ad{subscription=new se;domContainer;providerContainer;chromecastInitializer;logger=new Sr;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new de(f.STOPPED),seekState:new de({state:j.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!0),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),internalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({}),cameraOrientation:new de({x:0,y:0})};info={playbackState$:new g(f.STOPPED),position$:new g(0),duration$:new g(1/0),muted$:new g(!1),volume$:new g(1),availableQualities$:new g([]),availableQualitiesFps$:new g({}),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),currentQuality$:new g(void 0),isAutoQualityEnabled$:new g(!0),autoQualityLimitingAvailable$:new g(!1),autoQualityLimits$:new g({}),currentPlaybackRate$:new g(1),currentBuffer$:new g({start:0,end:0}),isBuffering$:new g(!0),isStalled$:new g(!1),isEnded$:new g(!1),isLooped$:new g(!1),isLive$:new g(void 0),canChangePlaybackSpeed$:new g(void 0),atLiveEdge$:new g(void 0),atLiveDurationEdge$:new g(void 0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),currentFormat$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),throughputEstimation$:new g(void 0),rttEstimation$:new g(void 0),videoBitrate$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),surface$:new g(xt.NONE),chromecastState$:new g(Le.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0),availableSources$:new g(void 0),is3DVideo$:new g(!1)};events={inited$:new I,ready$:new I,started$:new I,playing$:new I,paused$:new I,stopped$:new I,willStart$:new I,willResume$:new I,willPause$:new I,willStop$:new I,willDestruct$:new I,watchCoverageRecord$:new I,watchCoverageLive$:new I,managedError$:new I,fatalError$:new I,ended$:new I,looped$:new I,seeked$:new I,willSeek$:new I,firstBytes$:new I,firstFrame$:new I,canplay$:new I,log$:new I};experimental={element$:new g(void 0),tuningConfigName$:new g([]),enableDebugTelemetry$:new g(!1),dumpTelemetry:Ur};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Do(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Er({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new bi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const a=Reflect.get(t,i,s);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const c=n.map(u=>JSON.stringify(u,(l,p)=>{const S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),d=`Player.${String(i)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:L.WTF,message:h,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Po(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ao({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===f.STOPPED&&e.startTransitionTo(f.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==f.PLAYING&&t.startTransitionTo(f.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?M(document,"visibilitychange").pipe(be()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==f.PAUSED&&e.startTransitionTo(f.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==f.STOPPED&&e.startTransitionTo(f.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:j.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===Le.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===Le.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){w(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),be()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){w(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return xo(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const s=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+a.x,y:s.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){w(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(Y(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===j.None?void 0:t.position;return P(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(A(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(K(({from:e})=>e===f.STOPPED),be()).subscribe(()=>{this.initedAt=ne(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case f.READY:this.events.ready$.next();break;case f.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case f.PAUSED:this.events.paused$.next();break;case f.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case f.PAUSED:this.events.willPause$.next();break;case f.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case f.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===j.Requested?this.desiredState.seekState.setState({...n,state:j.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:L.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===j.Applying&&(this.desiredState.seekState.setState({state:j.None}),this.events.seeked$.next())})).add(e.current$.pipe(A(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(A(n=>n.destination),le()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(A(n=>n.map(({quality:o})=>o).sort((o,c)=>Ht(o)?1:Ht(c)?-1:Kt(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const c of n)c.fps&&(o[c.quality]=c.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.hostname$.pipe(le()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(le()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(le()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(A(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(xe({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(A(({isLive:n,position:o,isLowLatency:c})=>{const d=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),le(),Ii(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(xe({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(A(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),le(),Ii(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(A(n=>n.muted),le()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(A(n=>n.volume),le()).subscribe(this.info.volume$)).add(Os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(Zt(!0)),e.providerOutput.seekedEvent$.pipe(Zt(!1))).pipe(le()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(A(n=>({id:n?`No${n}`:"NoProviders",category:L.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(be(),A(n=>n??ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(be(),A(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(be(),A(()=>ne()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new g(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new g(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(K(({to:n})=>n===f.PLAYING),be()).subscribe(()=>i.next(!1)));let s=0;const a=O(e.providerOutput.isBuffering$,t,i).pipe(A(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),le());this.subscription.add(a.subscribe(n=>{n?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(O(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(O(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let h;d===Le.CONNECTED?h=xt.SECOND_SCREEN:c?n?h=xt.PIP:o?h=xt.FULLSCREEN:h=xt.INLINE:h=xt.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(A(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new se;this.subscription.add(t),this.subscription.add(e.current$.pipe(le((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),be()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Gt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(O(this.desiredState.videoTrack.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(A(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const e=this.providerContainer?.providerOutput;w(this.providerContainer),w(e),Vr(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Fr(t)),this.providerContainer.current$.subscribe(({type:t})=>wi("provider",t)),e.duration$.subscribe(t=>wi("duration",t)),e.availableVideoTracks$.pipe(K(t=>!!t.length),be()).subscribe(t=>wi("tracks",t)),this.events.fatalError$.subscribe(new lt("fatalError")),this.events.managedError$.subscribe(new lt("managedError")),e.position$.subscribe(new lt("position")),e.currentVideoTrack$.pipe(A(t=>t?.quality)).subscribe(new lt("quality")),this.info.currentBuffer$.subscribe(new lt("buffer")),e.isBuffering$.subscribe(new lt("isBuffering"))].forEach(t=>this.subscription.add(t)),wi("codecs",bo())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:L.DOM,message:String(s)})})};this.subscription.add(O(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===f.PLAYING,n=!!e&&!e?.released;s&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const nd=`@vkontakte/videoplayer-core@${Tr}`;export{Le as ChromecastState,yi as HttpConnectionType,cd as Observable,f as PlaybackState,ad as Player,nd as SDK_VERSION,ud as Subject,hd as Subscription,xt as Surface,Tr as VERSION,ld as ValueSubject,y as VideoFormat,fd as VideoQuality};
|
|
45
|
+
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class js{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new Za(this.params.fov,this.params.orientation),this.cameraRotationManager=new en(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(s,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(tn,this.gl.VERTEX_SHADER),i=this.createShader(sn,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,a=e-i,n=t-s,o=e+i,c=t-s,d=e+i,h=t+s,u=e-i,l=t+s;return[a,n,o,c,d,h,u,l]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let Js=class{scene3D;subscription=new se;videoState=new de(me.STOPPED);video;player;params;elementSize$=new m(void 0);textTracksManager=new nt;droppedFramesManager=new $i;videoTracks$=new m([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Us;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ka({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=yt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:L.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ct(this.video,t.isLooped,s)),this.subscription.add(gt(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(wt(this.video,t.playbackRate,i.playbackRateState$,s)),a(vi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===me.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Xe.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();D(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,w)=>w.bitrate-b.bitrate),p=Array.from(u.video).sort((b,w)=>w.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const w=Wa(b);w&&this.audioTracks.push({track:w,representation:b})}for(const b of p){const w=qa(b);if(w){h.push({track:w,representation:b});const C=!this.params.tuning.isAudioDisabled&&Qa(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const w=ja(b);w&&this.textTracks.push({track:w,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const v=this.selectVideoRepresentation();D(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Xe.REPRESENTATIOS_READY&&(this.videoState.setState(me.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Xe.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Ie.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Ie.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=Ye(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=Gt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===j.Requested&&i?.to!==f.PAUSED&&e!==me.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==me.STOPPED&&(this.videoState.startTransitionTo(me.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(me.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case me.STOPPED:this.videoState.startTransitionTo(me.READY),this.prepare();return;case me.READY:t===f.PAUSED?(this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case me.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case me.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new js(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){Dt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(me.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}},rn=class extends Js{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Ce;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(Ce||(Ce={}));var ht;(function(r){r[r.ActiveLowLatency=0]="ActiveLowLatency",r[r.LiveWithTargetOffset=1]="LiveWithTargetOffset",r[r.LiveForwardBuffering=2]="LiveForwardBuffering",r[r.None=3]="None"})(ht||(ht={}));var Fi;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Fi||(Fi={}));var et;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(et||(et={}));var Q;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(Q||(Q={}));var si;(function(r){r.MP4="mp4",r.WEBM="webm"})(si||(si={}));var Vi;(function(r){r[r.RECTANGULAR=0]="RECTANGULAR",r[r.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",r[r.CUBEMAP=2]="CUBEMAP",r[r.MESH=3]="MESH"})(Vi||(Vi={}));var ge;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ge||(ge={}));let Xs=!1;try{Xs=Gi().browser===ns.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class an{bufferFull$=new I;error$=new I;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const a={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Xs&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:L.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:L.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:N(t)}}}class tt{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Ks extends tt{}class nn extends tt{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class on extends tt{parseChildrenBoxes(){return Bt(this.content)}}class dn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class cn extends tt{data;constructor(e){super(e),this.data=this.content}}class Pt extends tt{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class un extends Pt{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class hn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class ln extends tt{parseChildrenBoxes(){return Bt(this.content)}}var Ut;(function(r){r[r.MONOSCOPIC=0]="MONOSCOPIC",r[r.TOP_BOTTOM=1]="TOP_BOTTOM",r[r.LEFT_RIGHT=2]="LEFT_RIGHT",r[r.STEREO_CUSTOM=3]="STEREO_CUSTOM",r[r.RIGHT_LEFT=4]="RIGHT_LEFT"})(Ut||(Ut={}));class fn extends Pt{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ut.MONOSCOPIC;break;case 1:this.stereoMode=Ut.TOP_BOTTOM;break;case 2:this.stereoMode=Ut.LEFT_RIGHT;break;case 3:this.stereoMode=Ut.STEREO_CUSTOM;break;case 4:this.stereoMode=Ut.RIGHT_LEFT;break}this.cursor+=1}}class pn extends Pt{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class mn extends Pt{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 gn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class Sn extends Pt{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 bn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class yn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class Tn extends Pt{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class vn extends tt{parseChildrenBoxes(){return Bt(this.content)}}class En extends Pt{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class kn extends Pt{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class $n extends Pt{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const An={ftyp:nn,moov:on,moof:dn,mdat:cn,sidx:un,trak:hn,mdia:gn,mfhd:Tn,tkhd:Sn,traf:vn,tfhd:En,tfdt:kn,trun:$n,minf:bn,sv3d:ln,st3d:fn,prhd:pn,proj:yn,equi:mn,unknown:Ks};class wn{createBox(e,t){const i=An[e];return i?new i(t):new Ks(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Qi.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Qi=new wn;function mi(r,e){const t=new Uint8Array(r.buffer),i=e.split("").map(n=>n.charCodeAt(0));let s=r.byteOffset,a=[];for(;s<t.byteLength;){if(t[s]===i[a.length]?a.push(t[s]):a=[],a.length===4){const o=new DataView(r.buffer,s-7,4).getUint32(0);return s-7+o>r.buffer.byteLength?null:Qi.createBox(e,new DataView(r.buffer,s-7))}s++}return null}function is(r,e){const t=[];let i=r.byteOffset;for(;i<r.buffer.byteLength;){const s=mi(new DataView(r.buffer,i,r.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function Bt(r){const e=[];let t=0;for(;t<r.byteLength;){const i=Qi.createFromView(new DataView(r.buffer,r.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Dn=new TextDecoder("ascii"),Pn=r=>Dn.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",xn=r=>{const e=Qi.createFromView(r);let t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Q.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Ln=r=>{const e=is(r,"mdat"),t=is(r,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],a=i.source.byteOffset,o=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(r.buffer,a,o)},Rn=(r,e)=>{const t=is(r,"traf"),i=t[t.length-1].children.find(c=>c.type==="tfhd"),s=t[t.length-1].children.find(c=>c.type==="tfdt"),a=t[t.length-1].children.find(c=>c.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((c,d)=>c+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(s.baseMediaDecodeTime)+n)/e*1e3},In=r=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Vi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(mi(r,"sv3d")){e.is3dVideo=!0;const i=mi(r,"st3d");i&&(e.stereoMode=i.stereoMode);const s=mi(r,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const a=mi(r,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Cn={validateData:Pn,parseInit:In,getIndexRange:()=>{},parseSegments:xn,parseFeedableSegmentChunk:Ln,getSegmentEndTime:Rn};var $;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.Video=224]="Video",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPrivate=30322]="ProjectionPrivate",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})($||($={}));var _;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(_||(_={}));const vs={[$.EBML]:{type:_.Master},[$.EBMLVersion]:{type:_.UnsignedInteger},[$.EBMLReadVersion]:{type:_.UnsignedInteger},[$.EBMLMaxIDLength]:{type:_.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[$.DocType]:{type:_.String},[$.DocTypeVersion]:{type:_.UnsignedInteger},[$.DocTypeReadVersion]:{type:_.UnsignedInteger},[$.Void]:{type:_.Binary},[$.Segment]:{type:_.Master},[$.SeekHead]:{type:_.Master},[$.Seek]:{type:_.Master},[$.SeekID]:{type:_.Binary},[$.SeekPosition]:{type:_.UnsignedInteger},[$.Info]:{type:_.Master},[$.TimestampScale]:{type:_.UnsignedInteger},[$.Duration]:{type:_.Float},[$.Tracks]:{type:_.Master},[$.TrackEntry]:{type:_.Master},[$.Video]:{type:_.Master},[$.Projection]:{type:_.Master},[$.ProjectionType]:{type:_.UnsignedInteger},[$.ProjectionPrivate]:{type:_.Master},[$.Chapters]:{type:_.Master},[$.Cluster]:{type:_.Master},[$.Timestamp]:{type:_.UnsignedInteger},[$.SilentTracks]:{type:_.Master},[$.SilentTrackNumber]:{type:_.UnsignedInteger},[$.Position]:{type:_.UnsignedInteger},[$.PrevSize]:{type:_.UnsignedInteger},[$.SimpleBlock]:{type:_.Binary},[$.BlockGroup]:{type:_.Master},[$.EncryptedBlock]:{type:_.Binary},[$.Attachments]:{type:_.Master},[$.Tags]:{type:_.Master},[$.Cues]:{type:_.Master},[$.CuePoint]:{type:_.Master},[$.CueTime]:{type:_.UnsignedInteger},[$.CueTrackPositions]:{type:_.Master},[$.CueTrack]:{type:_.UnsignedInteger},[$.CueClusterPosition]:{type:_.UnsignedInteger},[$.CueRelativePosition]:{type:_.UnsignedInteger},[$.CueDuration]:{type:_.UnsignedInteger},[$.CueBlockNumber]:{type:_.UnsignedInteger},[$.CueCodecState]:{type:_.UnsignedInteger},[$.CueReference]:{type:_.Master},[$.CueRefTime]:{type:_.UnsignedInteger}},Zs=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ui(r,t),s=i in vs,a=s?vs[i].type:_.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=n&255>>o,h=Ui(c),u=d*2**((o-1)*8)+h,l=t+o;let p;return l+u>r.byteLength?p=new DataView(r.buffer,r.byteOffset+l):p=new DataView(r.buffer,r.byteOffset+l,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+u,value:p,valueSize:u}},Ui=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{const t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},pt=(r,e)=>{switch(e){case _.SignedInteger:return r.getInt8(0);case _.UnsignedInteger:return Ui(r);case _.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(r);case _.UTF8:return new TextDecoder("utf-8").decode(r);case _.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case _.Master:return r;case _.Binary:return r;default:N(e)}},ri=(r,e)=>{let t=0;for(;t<r.byteLength;){const i=new DataView(r.buffer,r.byteOffset+t),s=Zs(i);if(!e(s))return;s.type===_.Master&&ri(s.value,e),t=s.value.byteOffset-r.byteOffset+s.valueSize}},Bn=r=>{if(r.getUint32(0)!==$.EBML)return!1;let e,t,i;const s=Zs(r);return ri(s.value,({tag:a,type:n,value:o})=>(a===$.EBMLReadVersion?e=pt(o,n):a===$.DocType?t=pt(o,n):a===$.DocTypeReadVersion&&(i=pt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},er=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],_n=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],Mn=r=>{let e,t,i,s,a=!1,n=!1,o=!1,c,d,h=!1;const u=0;return ri(r,({tag:l,type:p,value:S,valueSize:v})=>{if(l===$.SeekID){const b=pt(S,p);d=Ui(b)}else l!==$.SeekPosition&&(d=void 0);return l===$.Segment?(e=S.byteOffset,t=S.byteOffset+v):l===$.Info?a=!0:l===$.SeekHead?n=!0:l===$.TimestampScale?i=pt(S,p):l===$.Duration?s=pt(S,p):l===$.SeekPosition&&d===$.Cues?c=pt(S,p):l===$.Tracks?ri(S,({tag:b,type:w,value:C})=>b===$.ProjectionType?(h=pt(C,w)===1,!1):!0):a&&n&&er.includes(l)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:u,projectionType:Vi.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},On=r=>{if(Y(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Nn=(r,e)=>{let t=!1,i=!1;const s=o=>P(o.time)&&P(o.position),a=[];let n;return ri(r,({tag:o,type:c,value:d})=>{switch(o){case $.Cues:t=!0;break;case $.CuePoint:n&&s(n)&&a.push(n),n={};break;case $.CueTime:n&&(n.time=pt(d,c));break;case $.CueTrackPositions:break;case $.CueClusterPosition:n&&(n.position=pt(d,c));break;default:t&&er.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:h}=o,u=a[c+1];return{status:Q.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Fn=r=>{let e=0,t=!1;try{ri(r,i=>i.tag===$.Cluster?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):_n.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},Vn={validateData:Bn,parseInit:Mn,getIndexRange:On,parseSegments:Nn,parseFeedableSegmentChunk:Fn},Es=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),s=i?.[1]==="-"?-1:1,a={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},jt=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,a]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>Y(a)?o:Y(c)?a:a.padStart(parseInt(c,10),"0"))}return t},Un=(r,e)=>{const i=new DOMParser().parseFromString(r,"application/xml"),s={video:[],audio:[],text:[]},a=i.children[0],n=a.getElementsByTagName("Period")[0],o=n.children,c=a.getAttribute("type")==="dynamic",d=a.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const l=a.getAttribute("mediaPresentationDuration"),p=n.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(l)u=Es(l);else if(p){const g=Es(p);P(g)&&(u=g)}else v&&(u=parseInt(v,10));let b=0;const w=a.getAttribute("profiles")?.split(",")??[],C=w.includes(Fi.WEBM_AS_IN_FFMPEG)||w.includes(Fi.WEBM_AS_IN_SPEC)?si.WEBM:si.MP4;for(const g of o){const E=g.getAttribute("mimeType"),x=g.getAttribute("codecs"),H=g.getAttribute("contentType")??E?.split("/")[0],q=g.getAttribute("profiles")?.split(",")??[],F=g.querySelectorAll("Representation"),G=g.querySelector("SegmentTemplate");if(H===Ce.TEXT){for(const T of F){const V=T.getAttribute("id")||"",z=g.getAttribute("lang"),te=T.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(te,e).toString(),ke=V.includes("_auto");s[Ce.TEXT].push({id:V,lang:z,isAuto:ke,kind:Ce.TEXT,url:ye})}continue}for(const T of F){const V=T.getAttribute("mimeType")??E,z=T.getAttribute("codecs")??x??"",te=T.getAttribute("contentType")??V?.split("/")[0]??H,ye=g.getAttribute("profiles")?.split(",")??[],ke=parseInt(T.getAttribute("width")??"",10),U=parseInt(T.getAttribute("height")??"",10),re=parseInt(T.getAttribute("bandwidth")??"",10)/1e3,pe=T.getAttribute("frameRate")??"",$e=T.getAttribute("quality")??void 0,Be=pe?qi(pe):void 0,ot=T.getAttribute("id")??(b++).toString(10),oi=te==="video"?`${U}p`:te==="audio"?`${re}Kbps`:z,zt=`${ot}@${oi}`,ae=T.querySelector("BaseURL")?.textContent?.trim()??"",we=new URL(ae,e).toString(),Ve=[...w,...q,...ye];let De;const vt=T.querySelector("SegmentBase"),Te=T.querySelector("SegmentTemplate")??G;if(vt){const Ae=T.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,dt]=Ae.split("-").map(ze=>parseInt(ze,10)),Ue={from:Pe,to:dt},it=T.querySelector("SegmentBase")?.getAttribute("indexRange"),[_t,Et]=it?it.split("-").map(ze=>parseInt(ze,10)):[],st=it?{from:_t,to:Et}:void 0;De={type:et.BYTE_RANGE,url:we,initRange:Ue,indexRange:st}}else if(Te){const Ae={representationId:T.getAttribute("id")??void 0,bandwidth:T.getAttribute("bandwidth")??void 0},Pe=parseInt(Te.getAttribute("timescale")??"",10),dt=Te.getAttribute("initialization")??"",Ue=Te.getAttribute("media"),it=parseInt(Te.getAttribute("startNumber")??"",10)??1,_t=jt(dt,Ae);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Et=Te.querySelectorAll("SegmentTimeline S")??[],st=[];let ze=0,Mt="",qe=0;if(Et.length){let We=it,ve=0;for(const rt of Et){const He=parseInt(rt.getAttribute("d")??"",10),ct=parseInt(rt.getAttribute("r")??"",10)||0,kt=parseInt(rt.getAttribute("t")??"",10);ve=Number.isFinite(kt)?kt:ve;const di=He/Pe*1e3,wi=ve/Pe*1e3;for(let qt=0;qt<ct+1;qt++){const or=jt(Ue,{...Ae,segmentNumber:We.toString(10),segmentTime:(ve+qt*He).toString(10)}),hs=(wi??0)+qt*di,dr=hs+di;We++,st.push({time:{from:hs,to:dr},url:or})}ve+=(ct+1)*He,ze+=(ct+1)*di}qe=ve/Pe*1e3,Mt=jt(Ue,{...Ae,segmentNumber:We.toString(10),segmentTime:ve.toString(10)})}else if(P(u)){const ve=parseInt(Te.getAttribute("duration")??"",10)/Pe*1e3,rt=Math.ceil(u/ve);let He=0;for(let ct=1;ct<rt;ct++){const kt=jt(Ue,{...Ae,segmentNumber:ct.toString(10),segmentTime:He.toString(10)});st.push({time:{from:He,to:He+ve},url:kt}),He+=ve}qe=He,Mt=jt(Ue,{...Ae,segmentNumber:rt.toString(10),segmentTime:He.toString(10)})}const Ot={time:{from:qe,to:1/0},url:Mt};De={type:et.TEMPLATE,baseUrl:we,segmentTemplateUrl:Ue,initUrl:_t,totalSegmentsDurationMs:ze,segments:st,nextSegmentBeyondManifest:Ot,timescale:Pe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!te||!V)continue;const Ge={video:Ce.VIDEO,audio:Ce.AUDIO,text:Ce.TEXT}[te];Ge&&s[Ge].push({id:zt,kind:Ge,segmentReference:De,profiles:Ve,duration:u,bitrate:re,mime:V,codecs:z,width:ke,height:U,fps:Be,quality:$e})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:C,representations:s}},Hn=({id:r,width:e,height:t,bitrate:i,fps:s,quality:a})=>{const n=(a?ai(a):void 0)??It({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},Yn=({id:r,bitrate:e})=>({id:r,bitrate:e}),Gn=(r,e,t)=>{const i=e.indexOf(t);return r.at(Math.round(r.length*i/e.length))??r.at(-1)},zn=({id:r,lang:e,url:t,isAuto:i})=>({id:r,url:t,isAuto:i,type:"internal",language:e}),ks=r=>"size"in r,Wt=r=>r.type===et.TEMPLATE,ss=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);class $s{onLastSegment$=new m(!1);fullyBuffered$=new m(!1);playingRepresentation$=new m(void 0);playingRepresentationInit$=new m(void 0);error$=new I;gaps=[];subscription=new se;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new AbortController;destroyAbortController=new AbortController;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;constructor(e,t,i,s,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:c,compatibilityMode:d=!1,manifest:h}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=c,this.isLive=!!h?.dynamic,this.container=i,i){case si.MP4:this.containerParser=Cn;break;case si.WEBM:this.containerParser=Vn;break;default:N(i)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=oe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);D(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new an(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),a=this.parsedInitData.get(t.id);D(i,"No init buffer for starting representation"),D(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));switchTo=oe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);D(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Y(s)||Y(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),D(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const a=this.getCurrentPosition();P(a)&&(this.isLive||(i.forEach(n=>n.status=Q.NONE),this.pruneBuffer(a,1/0,!0)),this.maintain(a))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Y(e)||Y(this.downloadingRepresentationId)||Y(this.playingRepresentationId)||Y(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=Ye(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(a=u)}if(isFinite(this.bufferLimit)&&Oi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Ye(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===Q.FED&&!o.length&&Ye(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=i.at(-1);c&&c.status===Q.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+s}),i=a.time.to;P(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let a=0,n=t.length-1;do s.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=oe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d||!Wt(d.segmentReference))return;const h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);D(i);const s=this.segments.get(t);D(s,"No segments for starting representation");const a=this.initData.get(t);if(D(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!Wt(t.segmentReference))return;const i=t.segmentReference.segments.map(o=>({...o,status:Q.NONE,size:void 0})),s=this.segments.get(t.id)??[],a=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.floor(a)>=Math.floor(o.time.from)&&Math.floor(a)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!Wt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),a=jt(i.segmentTemplateUrl,{segmentTime:s}),n=this.segments.get(t.id)??[],o=n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||n.push({status:Q.NONE,time:{from:e.segment.time.to,to:1/0},url:a})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:u,time:{from:l,to:p}},S)=>{const v=l<=i&&p>=i,b=l>i||v||S===0&&i===0,w=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&l<=i+w||p<=i+w;return(u===Q.NONE||u===Q.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!ti(this.sourceBuffer.buffered,i))&&b&&C});if(s===-1)return[];if(t!==et.BYTE_RANGE)return e.slice(s,s+1);const a=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<a.length&&(n<=d||o<=h);u++){const l=a[u];if(n+=l.byte.to+1-l.byte.from,o+=l.time.to+1-l.time.from,l.status===Q.NONE||l.status===Q.PARTIALLY_EJECTED)c.push(l);else break}return c}async loadSegments(e,t,i="auto"){t.segmentReference.type===et.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Q.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:a,url:n,signal:o,onProgress:c,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await oe(o,async function*(){const h=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,h))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:c,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const u=new DataView(h);if(this.isActiveLowLatency()){const l=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(u,l)}c&&s.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(u,o),s.segment.status=Q.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!ss(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const c of e)c.status=Q.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await oe(n,async function*(){const c=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:s,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(c){if(!ss(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}}prepareByteRangeFetchSegmentParams(e,t){if(Wt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:s,signal:a,onProgress:(c,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const s=i.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,u)=>{if(!a.aborted)try{const l=this.onSomeTemplateDataLoaded({dataView:h,loaded:u,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:s,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&P(i)&&(t=Ye(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:L.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:c}=o;if(o.representationId===t){if(a.aborted){s();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(d);h?.byteLength&&(c.status=Q.PARTIALLY_FED,o.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),o.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const c=o.segmentReference.type,d=e.byteLength;for(const h of this.activeSegments){const{segment:u}=h,l=c===et.BYTE_RANGE,p=l?u.byte.to-u.byte.from+1:d;if(h.representationId!==t||!(!l||u.byte.from>=i&&u.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const v=l?u.byte.from-i:0,b=l?u.byte.to-i:e.byteLength,w=v<s,C=b<=s;if(u.status===Q.DOWNLOADING&&w&&C){u.status=Q.DOWNLOADED;const g=new DataView(e.buffer,e.byteOffset+v,p);this.sourceBufferTaskQueue.append(g,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(h,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&w&&(h.loadedBytes=Math.min(p,s-v),h.loadedBytes>h.feedingBytes)){const g=new DataView(e.buffer,e.byteOffset+v+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===p?g:this.containerParser.parseFeedableSegmentChunk(g);E?.byteLength&&(u.status=Q.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then(x=>{if(a.aborted)n();else if(x)h.fedBytes+=E.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Q.FED,ks(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===Q.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=Q.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?oe(this.destroyAbortController.signal,async function*(){const o=gi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:c,dataView:d,segments:h}=o,u=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,u);let l=h;this.isLive&&Wt(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Y(e)||this.sourceBuffer.updating)return!1;let s=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const h=ks(d)?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===Q.FED&&c(h)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===Q.FED&&c(h)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const l of this.segments.values())for(const p of l)if(p.status===Q.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(u)){a=h,n=u;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){s=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===Q.FED&&c(u)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(a=>s&&a.from===s.from&&a.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Y(this.sourceBuffer)||Y(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:a})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:a}=s;if(a!==Q.FED&&a!==Q.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=Q.PARTIALLY_EJECTED:s.status=Q.NONE)}}}var Xt;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(Xt||(Xt={}));class qn{throughputEstimator;requestQuic;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);abortAllController=new AbortController;subscription=new se;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=oe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Rt(t));const i=yield fetch(t,{signal:this.abortAllController.signal}).catch(hi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=oe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Xt.HEADER:Xt.PARAM,range:i,onProgress:s,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let d=e;const h=new Headers;if(i)switch(t){case Xt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Xt.PARAM:{const F=new URL(d,location.href);F.searchParams.append("bytes",`${i.from}-${i.to}`),d=F.toString();break}default:N(t)}this.requestQuic&&(d=Rt(d));let u=this.abortAllController.signal,l;if(n){const F=new AbortController;if(l=O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{F.abort()}catch(G){hi(G)}}),this.abortAllController.signal.aborted||n.aborted)try{F.abort()}catch(G){hi(G)}u=F.signal}const p=ne(),S=yield fetch(d,{priority:a,headers:h,signal:u}).catch(hi),v=ne();if(!S)return l?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-p),!S.ok||!S.body)return l?.unsubscribe(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));if(this.onHeadersReceived(S.headers),!s&&!o)return l?.unsubscribe(),S.arrayBuffer();const[b,w]=S.body.tee(),C=b.getReader();o&&this.throughputEstimator?.trackStream(w,c);let g=0,E=new Uint8Array(0),x=!1;const H=F=>{l?.unsubscribe(),x=!0,hi(F)},q=oe(u,async function*({done:F,value:G}){if(g===0&&this.lastRequestFirstBytes$.next(ne()-p),u.aborted){l?.unsubscribe();return}if(!F&&G){const T=new Uint8Array(E.length+G.length);T.set(E),T.set(G,E.length),E=T,g+=G.byteLength,s?.(new DataView(E.buffer),g),yield C?.read().then(q,H)}}.bind(this));return yield C?.read().then(q,H),l?.unsubscribe(),x?null:E.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case et.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case et.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:N(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=oe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==et.BYTE_RANGE)return null;const{from:s,to:a}=e.initRange;let n=s,o=a,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,s),o=Math.max(h,a))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l),S=e.indexRange??t.getIndexRange(p);if(!S)throw new ReferenceError("No way to load representation index");let v;if(c)v=new DataView(u,S.from-n,S.to-S.from+1);else{const w=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!w)return null;v=new DataView(w)}const b=t.parseSegments(v,p,S);return{init:p,dataView:new DataView(u),segments:b}}.bind(this));fetchTemplateRepresentation=oe(this.abortAllController.signal,async function*(e,t){if(e.type!==et.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(n=>({...n,status:Q.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const hi=r=>{if(!ss(r))throw r},rs=1e3,Hi=(r,e,t)=>t*e+(1-t)*r,tr=(r,e)=>r.reduce((t,i)=>t+i,0)/e,Wn=(r,e,t,i)=>{let s=0,a=t;const n=tr(r,e),o=e<i?e:i;for(let c=0;c<o;c++)r[a]>n?s++:s--,a=(r.length+a-1)%r.length;return Math.abs(s)===o};class us{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new m(e.initial),this.debounced$=new m(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new lt(`raw_${t}`),this.smoothedSeries$=new lt(`smoothed_${t}`),this.reportedSeries$=new lt(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(Y(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Qn extends us{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Hi(this.slow,e,this.params.emaAlphaSlow),this.fast=Hi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class jn extends us{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=tr(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Hi(this.emaSmoothed,e,this.params.emaAlpha);const i=Wn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Jn extends us{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?Hi(this.smoothed,e,this.params.emaAlpha):e}}class as{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Qn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new jn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Jn({initial:e,label:"liveEdgeDelay",...t})}}const Xn=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)},As=["timeupdate","progress","play","seeked","stalled","waiting"];var Ke;(function(r){r.NONE="none",r.MANIFEST_READY="manifest_ready",r.REPRESENTATIOS_READY="representations_ready",r.RUNNING="running"})(Ke||(Ke={}));let Kn=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new se;representationSubscription=new se;fetcher;state$=new de(Ke.NONE);currentVideoRepresentation$=new m(void 0);currentVideoRepresentationInit$=new m(void 0);error$=new I;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);isLive$=new m(!1);liveDuration$=new m(0);liveAvailabilityStartTime$=new m(void 0);bufferLength$=new m(0);liveLoadBufferLength$=new m(0);livePositionFromPlayer$=new m(0);liveEstimatedDelay;waitingEventInterval;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new qn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=as.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=oe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Oe(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ke.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Ke.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=oe(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Un(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:a,codecs:n})=>!!(this.element?.canPlayType?.(a)&&window.MediaSource?.isTypeSupported?.(`${a}; codecs="${n}"`)||s===Ce.TEXT);return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,a])=>[s,a.filter(i)]))}}.bind(this));async seekLive(e){D(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Oe(this.manifestUrlString,t,fe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initRepresentations=oe(this.destroyController.signal,async function*(e,t){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ke.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new $s(Ce.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],P(t)&&(this.audioBufferManager=new $s(Ce.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Yt(rs).subscribe(n=>{if(this.element?.paused){const o=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Oe(this.manifestUrlString,o+rs,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...As.map(n=>M(this.element,n))).pipe(A(n=>this.element?Ye(this.element.buffered,this.element.currentTime*1e3):0),le(),K(n=>!!n),yi(n=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(K(o=>this.isActiveLowLatency&&!!o)).subscribe(o=>this.liveEstimatedDelay.next(o))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(o=>{if(!this.isActiveLowLatency)return;const c=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,d=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,u=o-c;let l=1+Math.sign(u)*h;Math.abs(u)<d?l=1:Math.abs(u)>d*2&&(l=1+Math.sign(u)*h*2),Xn(this.element,l)})),this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(xe({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:o,bufferLength:c})=>{if(D(this.element),this.isUpdatingLive)return;const d=this.element.playbackRate,h=Ci(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,l=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*d),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*d,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*d,v=this.isActiveLowLatency?c:o;let b=ht.None;if(this.isActiveLowLatency?b=ht.ActiveLowLatency:v<l+S&&v>=l?b=ht.LiveWithTargetOffset:h!==0&&v<l&&(b=ht.LiveForwardBuffering),isFinite(o)&&(n=o>n?o:n),b===ht.LiveForwardBuffering||b===ht.LiveWithTargetOffset){const w=n-(l+p),C=this.normolizeLiveOffset(Math.trunc(h+w/d)),g=Math.abs(C-h);let E;!o||g<=this.tuning.dashCmafLive.offsetCalculationError?E=h:C>0&&g>this.tuning.dashCmafLive.offsetCalculationError?E=C:E=0,this.manifestUrlString=Oe(this.manifestUrlString,E,fe.DASH_CMAF_OFFSET_P)}b!==ht.None&&b!==ht.ActiveLowLatency&&(n=0,this.updateLive())}))}const s=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,xe({allBuffersFull:s,someBufferEnded:a}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(O(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(n=>this.source?.addEventListener("sourceopen",n))),P(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&P(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Ke.REPRESENTATIOS_READY)}.bind(this));initBuffer(){D(this.element),this.state$.setState(Ke.RUNNING),this.subscription.add(O(...As.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ti(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){return{[Ce.VIDEO]:this.videoBufferManager,[Ce.AUDIO]:this.audioBufferManager,[Ce.TEXT]:null}[e]?.switchTo(t)}seek(e,t){D(this.element),D(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ti(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ke.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:L.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Yt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const a of s.gaps)s.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class ir{scene3D;subscription=new se;videoState=new de(ge.STOPPED);video;player;params;elementSize$=new m(void 0);textTracksManager=new nt;droppedFramesManager=new $i;videoTracks$=new m([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Us;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Kn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=yt(this.video),s=this.constructor.name,a=o=>{e.error$.next({id:s,category:L.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,c)=>this.subscription.add(o.subscribe(c,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(A(d=>d.map(({track:h})=>h)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(K(P),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ct(this.video,t.isLooped,s)),this.subscription.add(gt(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(wt(this.video,t.playbackRate,i.playbackRateState$,s)),a(vi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),R(t.playbackState,f.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),R(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Ke.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();D(u,"Manifest not loaded or empty");const l=Array.from(u.audio).sort((b,w)=>w.bitrate-b.bitrate),p=Array.from(u.video).sort((b,w)=>w.bitrate-b.bitrate),S=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const b of l){const w=Yn(b);w&&this.audioTracks.push({track:w,representation:b})}for(const b of p){const w=Hn(b);if(w){h.push({track:w,representation:b});const C=!this.params.tuning.isAudioDisabled&&Gn(l,p,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(h);for(const b of S){const w=zn(b);w&&this.textTracks.push({track:w,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const v=this.selectVideoRepresentation();D(v),this.player.initRepresentations(v.id,this.audioRepresentations.get(v.id)?.id)}else d===Ke.REPRESENTATIOS_READY&&(this.videoState.setState(ge.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Ke.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(l&&this.params.output.autoVideoTrackLimits$.next(l.to),u){this.player.switchRepresentation(Ce.VIDEO,u.id).catch(n);const p=this.audioRepresentations.get(u.id);p&&this.player.switchRepresentation(Ce.AUDIO,p.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(le(),A(d=>d&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(A(({to:d})=>d===f.READY),le());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===f.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===f.READY)));const c=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),a=Ye(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),d=Gt(this.videoTracks$.getValue().map(({track:u})=>u),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:c,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?d??i:i??d;return h&&this.videoTracks$.getValue().find(({track:u})=>u===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===j.Requested&&i?.to!==f.PAUSED&&e!==ge.STOPPED&&t!==f.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===f.STOPPED){e!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ge.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}switch(e){case ge.STOPPED:this.videoState.startTransitionTo(ge.READY),this.prepare();return;case ge.READY:t===f.PAUSED?(this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):i?.to===f.READY&&R(this.params.desiredState.playbackState,f.READY);return;case ge.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ge.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new js(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){Dt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ge.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}}class Zn extends ir{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let eo=class extends Js{constructor(e){super(e),this.liveOffset=new ki}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(xe({interval:Yt(ts),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===me.PLAYING){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(xe({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===f.PAUSED&&i===me.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}};class to extends ir{constructor(e){super(e),this.liveOffset=new ki}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(xe({interval:Yt(rs),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ge.PLAYING&&!this.player.isActiveLowLatency){const a=e.position$.getValue()+(s-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(xe({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({liveBufferTime:s,liveAvailabilityStartTime:a})=>s&&a?s+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===f.PAUSED&&i===ge.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const ut={};var ie;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ie||(ie={}));const li=(r,e)=>new zi(t=>{const i=(s,a)=>t.next(a);return r.on(e,i),()=>r.off(e,i)});class io{subscription=new se;videoState=new de(ie.INITIALIZING);video;params;hls;textTracksManager=new nt;trackLevels=new Map;constructor(e){this.video=St(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),bt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:L.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(ut.Hls=s.default,ut.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){D(ut.Hls,"hls.js not loaded"),this.hls=new ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ie.STOPPED)}subscribe(){D(ut.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:L.WTF,message:"HlsJsProvider internal logic error",thrown:d})},s=yt(this.video),a=(d,h)=>this.subscription.add(d.subscribe(h,i));a(s.timeUpdate$,t.position$),a(s.durationChange$,t.duration$),a(s.ended$,t.endedEvent$),a(s.looped$,t.loopedEvent$),a(s.error$,t.error$),a(s.isBuffering$,t.isBuffering$),a(s.currentBuffer$,t.currentBuffer$),a(s.loadStart$,t.firstBytesEvent$),a(s.playing$,t.firstFrameEvent$),a(s.canplay$,t.canplay$),a(s.seeked$,t.seekedEvent$),a(s.inPiP$,t.inPiP$),a(s.inFullscreen$,t.inFullscreen$),this.subscription.add(Ct(this.video,e.isLooped,i)),this.subscription.add(gt(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(wt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(li(this.hls,ut.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:L.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),R(e.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),R(e.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),a(li(this.hls,ut.Events.MANIFEST_PARSED).pipe(A(({levels:d})=>d.reduce((h,u)=>{const l=u.name||u.height.toString(10),{width:p,height:S}=u,v=ai(u.attrs.QUALITY??"")??It({width:p,height:S});if(!v)return h;const b=u.attrs["FRAME-RATE"]?parseFloat(u.attrs["FRAME-RATE"]):void 0,w={id:l.toString(),quality:v,bitrate:u.bitrate/1e3,size:{width:p,height:S},fps:b};return this.trackLevels.set(l,{track:w,level:u}),h.push(w),h},[]))),t.availableVideoTracks$),a(li(this.hls,ut.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const h=[];for(const u of d.subtitleTracks){const l=u.name,p=u.attrs.URI||"",S=u.lang,v="internal";h.push({id:l,url:p,language:S,type:v})}e.internalTextTracks.startTransitionTo(h)}}),a(li(this.hls,ut.Events.LEVEL_LOADING).pipe(A(({url:d})=>Fe(d))),t.hostname$),this.subscription.add(at(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>Array.from(this.trackLevels.values()).find(({level:h})=>h===d)?.track,o=li(this.hls,ut.Events.LEVEL_SWITCHED).pipe(A(({level:d})=>n(this.hls.levels[d])));o.pipe(K(P)).subscribe(t.currentVideoTrack$,i),this.subscription.add(at(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{if(Y(d))return;const h=this.trackLevels.get(d.id)?.level;if(!h)return;const u=this.hls.levels.indexOf(h),l=this.hls.currentLevel,p=this.hls.levels[l];!p||h.bitrate>p.bitrate?this.hls.nextLevel=u:(this.hls.loadLevel=u,this.hls.loadLevel=u)},{changed$:o,onError:i})),a(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(c.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==ie.INITIALIZING)switch(i?.to!==f.PAUSED&&s.state===j.Requested&&this.seek(s.position),t){case f.STOPPED:switch(e){case ie.STOPPED:break;case ie.READY:case ie.PLAYING:case ie.PAUSED:this.stop();break;default:N(e)}break;case f.READY:switch(e){case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PLAYING:case ie.PAUSED:break;default:N(e)}break;case f.PLAYING:switch(e){case ie.PLAYING:break;case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PAUSED:this.playIfAllowed();break;default:N(e)}break;case f.PAUSED:switch(e){case ie.PAUSED:break;case ie.STOPPED:this.prepare();break;case ie.READY:this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED);break;case ie.PLAYING:this.pause();break;default:N(e)}break;default:N(t)}};prepare(){this.videoState.startTransitionTo(ie.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ie.PLAYING),await Dt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:t}))||(this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ie.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(ie.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0)}}const ws="X-Playback-Duration";var Ds=async r=>{const e=await fetch(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(ws)?parseInt(e.headers.get(ws),10):void 0};const so=r=>{let e=null;if(r.QUALITY&&(e=ai(r.QUALITY)),!e&&r.RESOLUTION){const[t,i]=r.RESOLUTION.split("x").map(s=>parseInt(s,10));e=It({width:t,height:i})}return e??null},sr=async(r,e=r)=>{const s=(await(await fetch(r)).text()).split(`
|
|
46
|
+
`),a=[],n=[];for(let o=0;o<s.length;o++){const c=s[o],d=c.match(/^#EXT-X-STREAM-INF:(.+)/),h=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!h)){if(d){const u=Object.fromEntries(d[1].split(",").map(C=>C.split("="))),l=u.QUALITY??`stream-${u.BANDWIDTH}`,p=so(u);let S;u.BANDWIDTH&&(S=parseInt(u.BANDWIDTH,10)/1e3||void 0),!S&&u["AVERAGE-BANDWIDTH"]&&(S=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let b;if(u.RESOLUTION){const[C,g]=u.RESOLUTION.split("x").map(E=>parseInt(E,10));C&&g&&(b={width:C,height:g})}const w=new URL(s[++o],e).toString();p&&a.push({id:l,quality:p,url:w,bandwidth:S,size:b,fps:v})}if(h){const u=Object.fromEntries(h[1].split(",").map(v=>v.split("=")).map(([v,b])=>[v,b.replace(/^"|"$/g,"")])),l=u.URI?.replace(/playlist$/,"subtitles.vtt"),p=u.LANGUAGE,S=u.NAME;l&&p&&n.push({type:"internal",id:p,label:S,language:p,url:l,isAuto:!1})}}}return{qualityManifests:a,textTracks:n}};var ce;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(ce||(ce={}));class ro{subscription=new se;videoState=new de(ce.STOPPED);video;params;textTracksManager=new nt;masterManifest;manifests$=new m([]);maxSeekBackTime$;liveOffset=new ki;manifestStartTime$=new m(void 0);constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Je.INVARIANT,url:this.params.source.url},sr(Oe(this.params.source.url),this.params.source.url).then(({qualityManifests:t})=>{if(t.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:L.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.maxSeekBackTime$=new m(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:L.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=yt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.ended$,e.endedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(gt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(wt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(le(),A(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Fe(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===ce.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===j.Requested&&this.seek(o.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(xe({startTime:this.manifestStartTime$.pipe(K(P)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),i)),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(Y(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:o,min:c}=t?.to??i??{};for(const[d,h]of[[o,"mq"],[c,"lq"]]){const u=String(parseFloat(d||""));h&&d&&s.searchParams.set(h,u)}}const a=this.params.format===y.HLS_LIVE_CMAF?fe.DASH_CMAF_OFFSET_P:fe.OFFSET_P,n=Oe(s.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",n),this.video.load(),Ds(n).then(o=>{if(!Y(o))this.maxSeekBackTime$.next(o);else{const c=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Y(c)||!isFinite(c))try{fetch(n).then(d=>d.text()).then(d=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(h){const u=new URL(h,n).toString();Ds(u).then(l=>{Y(l)||this.maxSeekBackTime$.next(l)})}})}catch{}}})}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(ce.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==f.PAUSED&&d.state===j.Requested){this.videoState.startTransitionTo(ce.READY),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case ce.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(ce.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ce.PAUSED:if(i===f.PLAYING)if(this.videoState.startTransitionTo(ce.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else s?.to===f.PAUSED&&(R(this.params.desiredState.playbackState,f.PAUSED),this.liveOffset.pause());return;case ce.CHANGING_MANIFEST:break;default:return N(t)}}}var he;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(he||(he={}));class ao{subscription=new se;videoState=new de(he.STOPPED);video;params;textTracksManager=new nt;masterManifest;manifests$=new m([]);constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Je.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),sr(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),a=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":a;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:L.WTF,message:"HlsProvider internal logic error",thrown:o})},s=yt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c));if(a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(wt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===he.READY&&this.videoState.setState(he.READY),this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const u=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const l=this.manifests$.getValue().find(p=>p.id===u);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(Fe(l.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===he.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===j.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:l})=>({id:c,quality:d,size:h,fps:l,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i)),!mr()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(O(M(o,"addtrack"),M(o,"removetrack"),M(o,"change"),Ne(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},i))}const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ne(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.selectManifest();if(Y(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:a,min:n}=t?.to??i??{};for(const[o,c]of[[a,"mq"],[n,"lq"]]){const d=String(parseFloat(o||""));c&&o&&s.searchParams.set(c,d)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===f.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(he.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(t===he.STOPPED){this.videoState.startTransitionTo(he.READY),this.prepare();return}if(a||n||o){const h=this.videoState.getState();this.videoState.setState(he.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:u}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:u*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&d.state===j.Requested&&this.seek(d.position),t){case he.READY:i===f.READY?R(this.params.desiredState.playbackState,f.READY):i===f.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):i===f.PLAYING&&(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed());return;case he.PLAYING:i===f.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):s?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case he.PAUSED:i===f.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;case he.CHANGING_MANIFEST:break;default:return N(t)}}}var Se;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Se||(Se={}));class no{subscription=new se;videoState=new de(Se.STOPPED);video;trackUrls={};params;textTracksManager=new nt;constructor(e){this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const a=s.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},s=yt(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,i));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.loadedMetadata$,e.firstBytesEvent$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.seeked$,e.seekedEvent$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(gt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(wt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING),R(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED),R(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Se.READY&&this.videoState.setState(Se.READY);const o=this.params.desiredState.videoTrack.getTransition();o&&P(o.to)&&(this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track)),this.videoState.getState()===Se.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;D(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];D(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Rt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Fe(t))}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===f.STOPPED){e!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Se.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!==Se.READY&&!n){this.handleQualityLimitTransition(a.to.max);return}if(e===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){const{currentTime:c}=this.video;this.prepare(),o.state===j.None&&this.params.desiredState.seekState.setState({state:j.Requested,position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==f.PAUSED&&o.state===j.Requested&&this.seek(o.position),e){case Se.READY:t===f.READY?R(this.params.desiredState.playbackState,f.READY):t===f.PAUSED?(this.videoState.setState(Se.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case Se.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(o=>!Ht(o.track.quality)&&Ns(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[a??"0"]?.track;if(s&&n&&Ki(n.quality,s.quality)&&(t=s),!t){const o=Object.values(this.trackUrls).filter(d=>!Ht(d.track.quality)&&Kt(d.track.quality,e)),c=o.length;c&&(t=o[c-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(a=>a.track);t=Gt(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}}const Ps=["stun:videostun.mycdn.me:80"],oo=1e3,co=3,Xi=()=>null;class uo{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Xi;externalStopCallback=Xi;externalErrorCallback=Xi;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Ps}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:L.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),oo)}normalizeOptions(e={}){const t={stunServerList:Ps,maxRetryNumber:co,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ue;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ue||(ue={}));class ho{subscription;params;log;video;videoState=new de(ue.STOPPED);liveStreamClient;maxSeekBackTime$=new m(0);constructor(e){this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=St(e.container),this.liveStreamClient=new uo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(this.videoState.stateChangeStarted$.pipe(A(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=yt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(s.timeUpdate$,e.liveTime$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ue.READY&&this.videoState.setState(ue.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(gt(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ue.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(f.STOPPED);break;case ue.READY:break;case ue.PAUSED:t.playbackState.setState(f.PAUSED);break;case ue.PLAYING:t.playbackState.setState(f.PLAYING);break;default:return N(n.to)}},i)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ne(["init"])).pipe(je(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Je.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,f.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ue.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:L.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Dt(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:L.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===f.STOPPED){e!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ue.STOPPED),R(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===ue.STOPPED){this.videoState.startTransitionTo(ue.READY),this.prepare();return}if(a){this.prepare();return}switch(e){case ue.READY:t===f.PAUSED?(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed());return;case ue.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):i?.to===f.PLAYING&&R(this.params.desiredState.playbackState,f.PLAYING);return;case ue.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&R(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}class xs{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const rr=Gi().device===gr.Android,Yi=document.createElement("video"),lo='video/mp4; codecs="avc1.42000a,mp4a.40.2"',fo='video/mp4; codecs="hev1.1.6.L93.B0"',ar='video/webm; codecs="vp09.00.10.08"',nr='video/webm; codecs="av01.0.00M.08"',po='audio/mp4; codecs="mp4a.40.2"',mo='audio/webm; codecs="opus"',Le={mms:!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(Yi.canPlayType?.("application/x-mpegurl")||Yi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Qe={mp4:!!Yi.canPlayType?.("video/mp4"),webm:!!Yi.canPlayType?.("video/webm"),cmaf:!0},mt={h264:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(lo),h265:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(fo),vp9:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(ar),av1:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(nr),aac:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(po),opus:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(mo)},Qt=(mt.h264||mt.h265)&&mt.aac;var Lt;(function(r){r.VP9="vp9",r.AV1="av1",r.NONE="none",r.SMOOTH="smooth",r.POWER_EFFICIENT="power_efficient"})(Lt||(Lt={}));var At;(function(r){r.DASH="dash",r.HLS="hls",r.MPEG="mpeg"})(At||(At={}));let Nt;const go=async()=>{if(!window.navigator.mediaCapabilities)return;const r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:nr}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:ar}})]);Nt={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{go()}catch(r){console.error(r)}const Ei=Le.hls&&Qe.mp4,So=()=>Object.keys(mt).filter(r=>mt[r]),bo=(r,e=!1,t=!1)=>r.filter(i=>{switch(i){case y.DASH:return Le.mse&&Qe.mp4&&Qt;case y.DASH_SEP:return(Le.mse||Le.mms&&t)&&Qe.mp4&&Qt;case y.DASH_WEBM:return(Le.mse||Le.mms&&t)&&Qe.webm&&mt.vp9&&mt.opus;case y.DASH_WEBM_AV1:return(Le.mse||Le.mms&&t)&&Qe.webm&&mt.av1&&mt.opus;case y.DASH_LIVE:return Le.mse&&Qe.mp4&&Qt;case y.DASH_LIVE_CMAF:return(Le.mse||Le.mms&&t)&&Qe.mp4&&Qt&&Qe.cmaf;case y.DASH_ONDEMAND:return(Le.mse||Le.mms&&t)&&Qe.mp4&&Qt;case y.HLS:case y.HLS_ONDEMAND:return Ei||e&&Le.mse&&Qe.mp4&&Qt;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return Ei;case y.MPEG:return Qe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Le.webrtc&&Le.ws&&mt.h264&&(Qe.mp4||Qe.webm);default:return N(i)}}),fi=r=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(r){case Lt.VP9:return[e,t];case Lt.AV1:return[t,e];case Lt.NONE:return[];case Lt.SMOOTH:return Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case Lt.POWER_EFFICIENT:return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:N(r)}return[e,t]},yo=({webmCodec:r,androidPreferredFormat:e})=>{if(rr)switch(e){case At.MPEG:return[y.MPEG,...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case At.HLS:return[y.HLS,y.HLS_ONDEMAND,...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case At.DASH:return[...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return Ei?[...fi(r),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...fi(r),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},To=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],s=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...s],n=[...s,...i];let o;if(rr)switch(r){case At.DASH:{o=a;break}case At.HLS:case At.MPEG:{o=n;break}}else Ei?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Ls=r=>r?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var vo=r=>new zi(e=>{const t=new se,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(A(({from:d,to:h})=>`${d}-${h}`)),s=r.desiredPlaybackState$.stateChangeEnded$,a=r.providerChanged$.pipe(A(({type:d})=>d!==void 0)),n=new I;let o=0,c="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),r.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(c),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Eo={cacheDuration:12e4},ko={chunkDuration:5e3,maxParallelRequests:5};class $o{current$=new m({type:void 0});providerError$=new I;noAvailableProvidersError$=new I;providerOutput={position$:new m(0),duration$:new m(1/0),volume$:new m({muted:!1,volume:1}),currentVideoTrack$:new m(void 0),availableVideoTracks$:new m([]),availableAudioTracks$:new m([]),isAudioAvailable$:new m(!0),autoVideoTrackLimitingAvailable$:new m(!1),autoVideoTrackLimits$:new m(void 0),currentBuffer$:new m(void 0),isBuffering$:new m(!0),error$:new I,warning$:new I,willSeekEvent$:new I,seekedEvent$:new I,loopedEvent$:new I,endedEvent$:new I,firstBytesEvent$:new I,firstFrameEvent$:new I,canplay$:new I,isLive$:new m(void 0),isLowLatency$:new m(!1),canChangePlaybackSpeed$:new m(!0),liveTime$:new m(void 0),liveBufferTime$:new m(void 0),availableTextTracks$:new m([]),currentTextTrack$:new m(void 0),hostname$:new m(void 0),httpConnectionType$:new m(void 0),httpConnectionReused$:new m(void 0),inPiP$:new m(!1),inFullscreen$:new m(!1),element$:new m(void 0),availableSources$:new m(void 0),is3DVideo$:new m(!1)};subscription=new se;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=bo([...To(this.params.tuning),...yo(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>P(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let a=[];i?a=[i]:s.length?a=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new xs(a),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(a);const n=[...Ls(!0),...Ls(!1)];this.chromecastFormatsIterator=new xs(n.filter(o=>P(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(console.log("Choose provider "+t),Y(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:L.WTF,message:"Failed to create provider",thrown:s})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),s=i.state!==j.None;if(this.params.desiredState.seekState.setState({state:j.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return N(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return D(o),new ha({...n,source:o,config:Eo})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJs?new ps({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new Zn({...n,source:o})):new rn({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJsCMAF?new ps({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new to({...n,source:o}):new eo({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),Ei||!this.params.tuning.useHlsJs?new ao({...n,source:o}):new io({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new ro({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return D(o),new no({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new na({...n,source:o,config:{...ko,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new ho({container:i,source:o,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return D(o),new Dr({connection:o,meta:a,container:i,source:t,format:e,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return N(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return N(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return N(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const a=new URL(s);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([s,a])=>[s,i(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,i=0;const s=ne();return e.add(O(this.providerOutput.error$,vo({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(A(a=>({id:`ProviderHangup:${a}`,category:L.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(K(({to:n})=>n===f.PLAYING),be()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(_e.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===L.NETWORK,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit,h=c&&(o&&t||!d),u=a.id.includes("partial_metadata"),l=ne()-s;h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u&&l<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():d?(i++,this.reinitProvider()):this.switchToNextProvider(n??_e.SCREEN)}})),e}}const Ao=5e3,Rs="one_video_throughput",Is="one_video_rtt",Si=window.navigator.connection,Cs=()=>{const r=Si?.downlink;if(P(r)&&r!==10)return r*1e3},Bs=()=>{const r=Si?.rtt;if(P(r)&&r!==3e3)return r},_s=(r,e,t)=>{const i=t*8,s=i/r;return i/(s+e)};class bi{throughput;rtt;subscription=new se;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=bi.load(Rs)||(e.useBrowserEstimation?Cs():void 0)||Ao,i=bi.load(Is)??(e.useBrowserEstimation?Bs():void 0)??0;if(this.throughput$=new m(t),this.rtt$=new m(i),this.rttAdjustedThroughput$=new m(_s(t,i,e.rttPenaltyRequestSize)),this.throughput=as.getSmoothedValue(t,-1,e),this.rtt=as.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=Cs();n&&this.throughput.next(n);const o=Bs();P(o)&&this.rtt.next(o)};Si&&"onchange"in Si&&this.subscription.add(M(Si,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{ji.set(Rs,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{ji.set(Is,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(xe({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(A(({throughput:s,rtt:a})=>_s(s,a,e.rttPenaltyRequestSize)),K(s=>{const a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ne();const s=new se;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(M(e,"progress").pipe(be()).subscribe(a=>{t=a.loaded,i=ne()}));break;case 1:case 0:s.add(M(e,"loadstart").subscribe(()=>{t=0,i=ne()}));break}s.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),c=n-t,d=o-i;this.addRawSpeed(c,d,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,a=ne(),n=0,o=ne();const c=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},d=async({done:h,value:u})=>{if(h)!t&&this.addRawSpeed(s,ne()-a,1),this.concurrentDownloads.delete(e);else if(u){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=u.byteLength;else{const p=o-a;p&&this.addRawSpeed(n,p,1,t),n=u.byteLength,a=ne()}o=ne()}else s+=u.byteLength,n+=u.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await i?.read().then(d,c)}};this.concurrentDownloads.add(e),i?.read().then(d,c)}addRawSpeed(e,t,i=1,s=!1){if(bi.sanityCheck(e,t,s)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=ji.get(e);if(P(t))return parseInt(t,10)??void 0}}const Ms={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Je.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Lt.VP9,androidPreferredFormat:At.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},wo=r=>({...Sr(r,Ms),configName:[...r.configName??[],...Ms.configName]});var Os=({seekState:r,position$:e})=>O(r.stateChangeEnded$.pipe(A(({to:t})=>t.state===j.None?void 0:(t.position??NaN)/1e3),K(P)),e.pipe(K(()=>r.getState().state===j.None))),Do=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return D(e,`Wrong container or containerId {${r.container}}`),e};const Po=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(K(s=>s.length>0),be()).subscribe(s=>{s.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};class id{subscription=new se;domContainer;providerContainer;chromecastInitializer;logger=new br;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new de(f.STOPPED),seekState:new de({state:j.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!0),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),internalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({}),cameraOrientation:new de({x:0,y:0})};info={playbackState$:new m(f.STOPPED),position$:new m(0),duration$:new m(1/0),muted$:new m(!1),volume$:new m(1),availableQualities$:new m([]),availableQualitiesFps$:new m({}),availableAudioTracks$:new m([]),isAudioAvailable$:new m(!0),currentQuality$:new m(void 0),isAutoQualityEnabled$:new m(!0),autoQualityLimitingAvailable$:new m(!1),autoQualityLimits$:new m({}),currentPlaybackRate$:new m(1),currentBuffer$:new m({start:0,end:0}),isBuffering$:new m(!0),isStalled$:new m(!1),isEnded$:new m(!1),isLooped$:new m(!1),isLive$:new m(void 0),canChangePlaybackSpeed$:new m(void 0),atLiveEdge$:new m(void 0),atLiveDurationEdge$:new m(void 0),liveTime$:new m(void 0),liveBufferTime$:new m(void 0),currentFormat$:new m(void 0),availableTextTracks$:new m([]),currentTextTrack$:new m(void 0),throughputEstimation$:new m(void 0),rttEstimation$:new m(void 0),videoBitrate$:new m(void 0),hostname$:new m(void 0),httpConnectionType$:new m(void 0),httpConnectionReused$:new m(void 0),surface$:new m(xt.NONE),chromecastState$:new m(Re.NOT_AVAILABLE),chromecastDeviceName$:new m(void 0),intrinsicVideoSize$:new m(void 0),availableSources$:new m(void 0),is3DVideo$:new m(!1)};events={inited$:new I,ready$:new I,started$:new I,playing$:new I,paused$:new I,stopped$:new I,willStart$:new I,willResume$:new I,willPause$:new I,willStop$:new I,willDestruct$:new I,watchCoverageRecord$:new I,watchCoverageLive$:new I,managedError$:new I,fatalError$:new I,ended$:new I,looped$:new I,seeked$:new I,willSeek$:new I,firstBytes$:new I,firstFrame$:new I,canplay$:new I,log$:new I};experimental={element$:new m(void 0),tuningConfigName$:new m([]),enableDebugTelemetry$:new m(!1),dumpTelemetry:Vr};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=wo(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new vr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new bi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const a=Reflect.get(t,i,s);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const c=n.map(u=>JSON.stringify(u,(l,p)=>{const S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),d=`Player.${String(i)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:L.WTF,message:h,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Do(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new $o({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===f.STOPPED&&e.startTransitionTo(f.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==f.PLAYING&&t.startTransitionTo(f.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?M(document,"visibilitychange").pipe(be()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==f.PAUSED&&e.startTransitionTo(f.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==f.STOPPED&&e.startTransitionTo(f.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:j.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===Re.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===Re.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){D(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),be()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){D(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Po(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const s=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+a.x,y:s.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(Y(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===j.None?void 0:t.position;return P(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(A(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(K(({from:e})=>e===f.STOPPED),be()).subscribe(()=>{this.initedAt=ne(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case f.READY:this.events.ready$.next();break;case f.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case f.PAUSED:this.events.paused$.next();break;case f.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case f.PAUSED:this.events.willPause$.next();break;case f.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case f.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===j.Requested?this.desiredState.seekState.setState({...n,state:j.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:L.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===j.Applying&&(this.desiredState.seekState.setState({state:j.None}),this.events.seeked$.next())})).add(e.current$.pipe(A(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(A(n=>n.destination),le()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(A(n=>n.map(({quality:o})=>o).sort((o,c)=>Ht(o)?1:Ht(c)?-1:Kt(c,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const c of n)c.fps&&(o[c.quality]=c.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.hostname$.pipe(le()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(le()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(le()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(A(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(xe({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(A(({isLive:n,position:o,isLowLatency:c})=>{const d=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),le(),yi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(xe({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(A(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),le(),yi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(A(n=>n.muted),le()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(A(n=>n.volume),le()).subscribe(this.info.volume$)).add(Os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(Zt(!0)),e.providerOutput.seekedEvent$.pipe(Zt(!1))).pipe(le()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(A(n=>({id:n?`No${n}`:"NoProviders",category:L.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(be(),A(n=>n??ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(be(),A(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(be(),A(()=>ne()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new m(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new m(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(K(({to:n})=>n===f.PLAYING),be()).subscribe(()=>i.next(!1)));let s=0;const a=O(e.providerOutput.isBuffering$,t,i).pipe(A(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),le());this.subscription.add(a.subscribe(n=>{n?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(O(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(O(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let h;d===Re.CONNECTED?h=xt.SECOND_SCREEN:c?n?h=xt.PIP:o?h=xt.FULLSCREEN:h=xt.INLINE:h=xt.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(A(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new se;this.subscription.add(t),this.subscription.add(e.current$.pipe(le((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),be()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Gt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(O(this.desiredState.videoTrack.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(A(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const e=this.providerContainer?.providerOutput;D(this.providerContainer),D(e),Fr(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Nr(t)),this.providerContainer.current$.subscribe(({type:t})=>Di("provider",t)),e.duration$.subscribe(t=>Di("duration",t)),e.availableVideoTracks$.pipe(K(t=>!!t.length),be()).subscribe(t=>Di("tracks",t)),this.events.fatalError$.subscribe(new lt("fatalError")),this.events.managedError$.subscribe(new lt("managedError")),e.position$.subscribe(new lt("position")),e.currentVideoTrack$.pipe(A(t=>t?.quality)).subscribe(new lt("quality")),this.info.currentBuffer$.subscribe(new lt("buffer")),e.isBuffering$.subscribe(new lt("isBuffering"))].forEach(t=>this.subscription.add(t)),Di("codecs",So())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:L.DOM,message:String(s)})})};this.subscription.add(O(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===f.PLAYING,n=!!e&&!e?.released;s&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const sd=`@vkontakte/videoplayer-core@${yr}`;export{Re as ChromecastState,Ti as HttpConnectionType,nd as Observable,f as PlaybackState,id as Player,sd as SDK_VERSION,od as Subject,dd as Subscription,xt as Surface,yr as VERSION,cd as ValueSubject,y as VideoFormat,ud as VideoQuality};
|