@vkontakte/videoplayer-core 2.0.98-dev.72824ff7.0 → 2.0.98-dev.97d8def3.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 +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +7 -7
- package/evergreen.esm.js +5 -5
- package/package.json +1 -1
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.98-dev.
|
|
3
|
-
* Thu, 15 Feb 2024
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.97d8def3.0
|
|
3
|
+
* Thu, 15 Feb 2024 16:10:49 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
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.72824ff7.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:`
|
|
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.97d8def3.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
|
`)}
|
|
@@ -42,5 +42,5 @@ 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 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(){console.log("destroy DASH provider"),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=>{console.log(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};
|
|
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]));console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(t);const{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 _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return N(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return 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:{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?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};
|