@vkontakte/videoplayer-core 2.0.92-dev.e8ee183.0 → 2.0.92

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/evergreen.esm.js CHANGED
@@ -1,38 +1,38 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.92-dev.e8ee183.0
3
- * Sun, 12 Nov 2023 21:51:33 GMT
2
+ * @vkontakte/videoplayer-core v2.0.92
3
+ * Thu, 16 Nov 2023 17:30:22 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-92/doc/
5
5
  */
6
- import{ValueSubject as f,Subject as L,Subscription as te,isNonNullable as A,ErrorCategory as R,isNullable as j,fromEvent as C,assertNever as O,merge as M,tap as ti,map as v,observableFrom as De,filterChanged as he,assertNonNullable as w,debounce as Be,getHighestQuality as Ps,timeout as Ds,getCurrentBrowser as Li,CurrentClientBrowser as ns,combine as $e,once as le,mapTo as wt,filter as J,now as re,videoSizeToQuality as St,isInvariantQuality as Ut,isHigher as Nt,isLower as Zt,isHigherOrEqual as Ei,isLowerOrEqual as os,Observable as hi,interval as ii,VideoQuality as Re,videoQualityToHeight as xs,abortable as Ee,getExponentialDelay as yi,CurrentClientDevice as Ls,safeStorage as Ti,fillWithDefault as _s,Logger as Rs}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as dn,Subject as cn,Subscription as hn,ValueSubject as un,VideoQuality as ln}from"@vkontakte/videoplayer-shared/esnext.esm.js";import Cs from"lodash/debounce.js";const Is="2.0.92-dev.e8ee183.0";var l;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(l||(l={}));var g;(function(a){a.MPEG="MPEG",a.DASH="DASH",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(g||(g={}));var ye;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ye||(ye={}));var ge;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(ge||(ge={}));var Ht;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Ht||(Ht={}));var Y;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(Y||(Y={}));var nt;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(nt||(nt={}));var Bs=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Ms{connection$=new f(void 0);castState$=new f(ge.NOT_AVAILABLE);errorEvent$=new L;contentId;realCastState$=new f(ge.NOT_AVAILABLE);subscription=new te;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const i=A(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},s||Bs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.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(){A(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();j(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();j(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(C(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return O(s.sessionState)}})).add(M(C(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ti(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),v(s=>s.castState)),De([i.getCastState()])).pipe(he(),v(Os),ti(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const r=s===ge.CONNECTED,n=A(this.connection$.getValue());if(r&&!n){const o=i.getCurrentSession();w(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(j(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!r&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===ge.CONNECTED?A(this.connection$.getValue())?ge.CONNECTED:ge.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Os=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return O(a)}};var fe;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Qe=(a,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{const i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:O(t)}return a};const Mi=(a,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:O(e)}};var D=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class oe{state;prevState;transition;transitionStarted$=new L;transitionEnded$=new L;transitionUpdated$=new L;forceChanged$=new L;stateChangeStarted$=M(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=M(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||A(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 Ns=a=>{switch(a){case g.MPEG:case g.DASH:case g.DASH_SEP:case g.DASH_ONDEMAND:case g.DASH_WEBM:case g.DASH_WEBM_AV1:case g.HLS:case g.HLS_ONDEMAND:return!1;case g.DASH_LIVE:case g.DASH_LIVE_CMAF:case g.HLS_LIVE:case g.HLS_LIVE_CMAF:case g.DASH_LIVE_WEBM:case g.WEB_RTC_LIVE:return!0;default:return O(a)}};var V;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const Fs=5,Vs=5,Us=500,Oi=7e3;class Hs{subscription=new te;loadMediaTimeoutSubscription=new te;videoState=new oe(V.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ns(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new te;this.subscription.add(e),this.subscription.add(M(this.videoState.stateChangeStarted$.pipe(v(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(v(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,r)=>this.subscription.add(s.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new L;e.add(s.pipe(Be(Us)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===Y.Applying||Math.abs(o-r)>Fs)&&s.next(o),r=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:r}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&r.duration-r.currentTime<Vs&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(this.params.desiredState.playbackState,l.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:O(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=M(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(Be(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&D(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,r;switch(e){case g.MPEG:{const d=t[e];w(d);const h=Ps(Object.keys(d));w(h);const u=d[h];w(u),i=u,s="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case g.HLS:case g.HLS_ONDEMAND:{const d=t[e];w(d),i=d.url,s="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case g.DASH_SEP:case g.DASH_ONDEMAND:case g.DASH_WEBM:case g.DASH_WEBM_AV1:{const d=t[e];w(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case g.DASH_LIVE_CMAF:{const d=t[e];w(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case g.HLS_LIVE:case g.HLS_LIVE_CMAF:{const d=t[e];w(d),i=Qe(d.url),s="application/x-mpegurl",r=chrome.cast.media.StreamType.LIVE;break}case g.DASH:case g.DASH_LIVE:case g.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:d,thrown:h}),h}case g.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=r,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return A(o)&&(n.metadata.title=o),A(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===Y.Applying||i.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,r)=>{this.loadMediaTimeoutSubscription.add(Ds(Oi).subscribe(()=>r(`timeout(${Oi})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.VIDEO_PIPELINE,message:r,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!t){if(s?.to!==l.PAUSED&&r.state===Y.Requested&&e!==V.STOPPED){this.seek(r.position/1e3);return}switch(i){case l.READY:{switch(e){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:O(e)}break}case l.PLAYING:{switch(e){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:O(e)}break}case l.PAUSED:{switch(e){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:O(e)}break}default:O(i)}}}}var Ys=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,r=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>r(n),t&&i&&e?.()}}},!0)},Gs=a=>{const e=new f(1/0),t=new L,i=new f(void 0),s=new f(void 0);let r=NaN,n=!1;const o=()=>{r=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(b=>b.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const b=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),T=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??b*1e3??NaN;A(T)&&!isNaN(T)&&e.next(T)}const p=u["x-delivery-type"]??Ht.HTTP1,S={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(p),s.next(S)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-r))};return a.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(p){if(p.request.type==="MPD"){const S=p.onload,b=p.progress;p.onload=function(...$){return c(this),S(...$)},p.progress=function(...$){return d(this),b(...$)},o()}return u(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},Pt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},zs=a=>a.extend("RequestModifier",()=>({modifyRequestURL:Pt}),!0),qs=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,r]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${r}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Ue=(a,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:r}={})=>{const n=a.getState(),o=e(),c=j(s),d=new te;return s&&d.add(s.subscribe(h=>{const u=a.getState();i(h,u)&&a.setState(h)},r)),i(o,n)||(t(n),c&&a.setState(n)),d.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),c&&a.setState(h.to)},r)),d},bt=(a,e,t)=>Ue(e,()=>a.loop,i=>{A(i)&&(a.loop=i)},{onError:t}),Ze=(a,e,t,i)=>Ue(e,()=>({muted:a.muted,volume:a.volume}),s=>{A(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,r)=>s===r||s?.muted===r?.muted&&s?.volume===r?.volume,changed$:t,onError:i}),ct=(a,e,t,i)=>Ue(e,()=>a.playbackRate,s=>{A(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),Ws=a=>["__",a.language,a.label].join("|"),Qs=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class je{available$=new L;current$=new f(void 0);error$=new L;video;cueSettings;subscription=new te;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=r=>{this.error$.next({id:"TextTracksManager",category:R.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ue(t.internalTextTracks,()=>Object.values(this.internalTracks),r=>{A(r)&&this.setInternal(r)},{equal:(r,n)=>A(r)&&A(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(v(r=>r.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(Ue(t.externalTextTracks,()=>Object.values(this.externalTracks),r=>{A(r)&&this.setExternal(r)},{equal:(r,n)=>A(r)&&A(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(v(r=>r.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(Ue(t.currentTextTrack,()=>{if(this.video)return;const r=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return r&&this.htmlTextTrackToITextTrack(r).id},r=>this.select(r),{changed$:this.current$,onError:s})),this.subscription.add(Ue(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){w(this.video);const{textTracks:e}=this.video;this.subscription.add(C(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(M(C(e,"addtrack"),C(e,"removetrack"),De(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),he((i,s)=>i.length===s.length&&i.every(({id:r},n)=>r===s[n].id))).subscribe(this.available$)),this.subscription.add(M(C(e,"change"),De(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),v(i=>i&&this.htmlTextTrackToITextTrack(i).id),he()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(C(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(C(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;A(t.align)&&(s.align=t.align),A(t.position)&&(s.position=t.position),A(t.size)&&(s.size=t.size),A(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){w(this.video);const t=[...this.video.textTracks];return e?t:t.filter(je.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Ws(e),r=this.externalTracks.has(s),n=s.includes("auto");return r?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(s)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t)))}select(e){w(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(j(e)||!Qs(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){w(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){w(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const _i=a=>{a.removeAttribute("src"),a.load()},js=a=>{try{a.pause(),a.playbackRate=0,_i(a),a.remove()}catch(e){console.error(e)}};class Js{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 $i=window.WeakMap?new WeakMap:new Js,et=a=>{let e=a.querySelector("video");const t=!!e;return e?_i(e):(e=document.createElement("video"),a.appendChild(e)),$i.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},tt=a=>{const e=$i.get(a);$i.delete(a),e?_i(a):js(a)};class ui{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 ds=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ni=a=>{const e=ds(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Xs=a=>{const e=ds(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ai=3;class Ks{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const r=this._source.buffered.end(t);s>e&&s-e<Ai&&(s=e),this._buffer.push({from:s,to:r,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ai))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:r})=>{const n=s>=e&&s<t,o=r>=e&&r<t;n&&o||(n?i(t,r):o?i(s,e):s<e&&r>t?(i(t,r),i(s,e)):i(s,r))})}destroy(){this._buffer=[]}}var cs=(a,e,t=Ai)=>{let i=0,s=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=r-1;c>=0;c--)a.end(c)+t>=i&&(i=a.start(c));for(let c=r+1;c<a.length;c++)a.start(c)-t<=s&&(s=a.end(c))}}return{from:i,to:s}};const it=a=>{const e=m=>C(a,m).pipe(wt(void 0)),i=M(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>C(a,m))).pipe(v(m=>m.type==="ended"?a.readyState<2:a.readyState<3),he()),s=M(C(a,"progress"),C(a,"timeupdate")).pipe(v(()=>cs(a.buffered,a.currentTime))),n=Li().browser===ns.Safari?$e({play:e("play").pipe(le()),playing:e("playing")}).pipe(wt(void 0)):e("playing"),o=C(a,"volumechange").pipe(v(()=>({muted:a.muted,volume:a.volume}))),c=C(a,"ratechange").pipe(v(()=>a.playbackRate)),d=C(a,"error").pipe(J(()=>!!(a.error||a.played.length)),v(()=>{const m=a.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=C(a,"timeupdate").pipe(v(()=>a.currentTime)),u=new L,p=.3;let S;h.subscribe(m=>{a.loop&&A(S)&&A(m)&&S>=a.duration-p&&m<=p&&u.next(S),S=m});const b=C(a,"enterpictureinpicture"),$=C(a,"leavepictureinpicture"),T=new f(Xs(a));b.subscribe(()=>T.next(!0)),$.subscribe(()=>T.next(!1));const _=new f(Ni(a));return C(a,"fullscreenchange").pipe(v(()=>Ni(a))).subscribe(_),{playing$:n,pause$:e("pause").pipe(J(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:C(a,"durationchange").pipe(v(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:T,inFullscreen$:_}},Ri=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let Ci=!1,Xe={};const Zs=a=>{Ci=a},ea=()=>{Xe={}},ta=a=>{a(Xe)},Jt=(a,e)=>{Ci&&(Xe.meta=Xe.meta??{},Xe.meta[a]=e)};class ze{name;constructor(e){this.name=e}next(e){if(!Ci)return;Xe.series=Xe.series??{};const t=Xe.series[this.name]??[];t.push([Date.now(),e]),Xe.series[this.name]=t}}var mt;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(mt||(mt={}));const ia=new ze("best_bitrate"),sa=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class aa{last;history={};recordSelection(e){this.history[e.id]=re()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Lt=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{const p=i.usePixelRatio?window.devicePixelRatio??1:1,S=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},b=S&&St(S),$=i.considerPlaybackRate&&A(o)?o:1,T=a.filter(P=>!Ut(P.quality)).sort((P,K)=>Nt(P.quality,K.quality)?-1:1),_=T.at(-1)?.quality,G=T.at(0)?.quality,m=j(s)||A(s.min)&&A(s.max)&&Zt(s.max,s.min)||A(s.min)&&G&&Nt(s.min,G)||A(s.max)&&_&&Zt(s.max,_),E=$*sa(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},Q=T.filter(P=>(b?Zt(P.quality,b):!0)?(A(t)&&isFinite(t)&&A(P.bitrate)?t-r>=P.bitrate*E:!0)?i.lazyQualitySwitch&&A(i.minBufferToSwitchUp)&&c&&!Ut(c.quality)&&(n??0)<i.minBufferToSwitchUp&&Nt(P.quality,c.quality)?(k[P.quality]=mt.Buffer,!1):!!h&&Ei(P.quality,h)?(k[P.quality]=mt.DroppedFramesLimit,!1):m||(j(s.max)||os(P.quality,s.max))&&(j(s.min)||Ei(P.quality,s.min))?!0:(k[P.quality]=mt.FitsQualityLimits,!1):(k[P.quality]=mt.FitsThroughput,!1):(k[P.quality]=mt.FitsContainer,!1))[0];Q&&Q.bitrate&&ia.next(Q.bitrate);const B=Q??T[Math.ceil((T.length-1)/2)]??a[0];B.quality!==d?.last?.quality&&u({message:`
7
- [available tracks] ${a.map(P=>P.quality).join(", ")}
6
+ import{ValueSubject as m,Subject as x,Subscription as te,isNonNullable as w,ErrorCategory as C,isNullable as J,fromEvent as L,assertNever as M,merge as B,tap as Kt,map as y,observableFrom as Ee,filterChanged as ce,assertNonNullable as P,debounce as Ie,getHighestQuality as vs,timeout as Es,getCurrentBrowser as $i,CurrentClientBrowser as es,combine as De,once as le,mapTo as Tt,filter as K,now as ue,videoSizeToQuality as pt,isInvariantQuality as Nt,isHigher as It,isLower as Jt,isHigherOrEqual as Si,isLowerOrEqual as ts,Observable as ni,interval as Zt,VideoQuality as Re,videoQualityToHeight as $s,abortable as Pe,getExponentialDelay as _i,throttle as ks,CurrentClientDevice as As,safeStorage as fi,fillWithDefault as ws,Logger as Ps}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as Xr,Subject as Kr,Subscription as Zr,ValueSubject as en,VideoQuality as tn}from"@vkontakte/videoplayer-shared/esnext.esm.js";import Ds from"lodash/debounce.js";const _s="2.0.92";var l;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(l||(l={}));var S;(function(a){a.MPEG="MPEG",a.DASH="DASH",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(S||(S={}));var Te;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(Te||(Te={}));var ge;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(ge||(ge={}));var Ot;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Ot||(Ot={}));var H;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(H||(H={}));var st;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(st||(st={}));var xs=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Rs{connection$=new m(void 0);castState$=new m(ge.NOT_AVAILABLE);errorEvent$=new x;contentId;realCastState$=new m(ge.NOT_AVAILABLE);subscription=new te;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const i=w(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},s||xs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){w(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();J(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();J(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(L(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return M(s.sessionState)}})).add(B(L(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Kt(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),y(s=>s.castState)),Ee([i.getCastState()])).pipe(ce(),y(Cs),Kt(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const r=s===ge.CONNECTED,n=w(this.connection$.getValue());if(r&&!n){const o=i.getCurrentSession();P(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(J(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!r&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===ge.CONNECTED?w(this.connection$.getValue())?ge.CONNECTED:ge.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Cs=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return M(a)}};var fe;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(fe||(fe={}));var Ye=(a,e=0,t=fe.OFFSET_P)=>{switch(t){case fe.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case fe.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case fe.DASH_CMAF_OFFSET_P:{if(e===0)return a;const i=new URL(a);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:M(t)}return a};const xi=(a,e)=>{switch(e){case fe.OFFSET_P:return NaN;case fe.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case fe.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:M(e)}};var D=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class ne{state;prevState;transition;transitionStarted$=new x;transitionEnded$=new x;transitionUpdated$=new x;forceChanged$=new x;stateChangeStarted$=B(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=B(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||w(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Ls=a=>{switch(a){case S.MPEG:case S.DASH:case S.DASH_SEP:case S.DASH_ONDEMAND:case S.DASH_WEBM:case S.DASH_WEBM_AV1:case S.HLS:case S.HLS_ONDEMAND:return!1;case S.DASH_LIVE:case S.DASH_LIVE_CMAF:case S.HLS_LIVE:case S.HLS_LIVE_CMAF:case S.DASH_LIVE_WEBM:case S.WEB_RTC_LIVE:return!0;default:return M(a)}};var V;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const Is=5,Bs=5,Ms=500,Ri=7e3;class Ns{subscription=new te;loadMediaTimeoutSubscription=new te;videoState=new ne(V.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ls(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new te;this.subscription.add(e),this.subscription.add(B(this.videoState.stateChangeStarted$.pipe(y(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(y(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,r)=>this.subscription.add(s.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new x;e.add(s.pipe(Ie(Ms)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(L(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===H.Applying||Math.abs(o-r)>Is)&&s.next(o),r=o})),e.add(L(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(L(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(L(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(L(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:r}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&r.duration-r.currentTime<Bs&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(this.params.desiredState.playbackState,l.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:M(n)}}),t(L(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(L(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=B(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ee(["init"])).pipe(Ie(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:H.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&D(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,r;switch(e){case S.MPEG:{const d=t[e];P(d);const h=vs(Object.keys(d));P(h);const u=d[h];P(u),i=u,s="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case S.HLS:case S.HLS_ONDEMAND:{const d=t[e];P(d),i=d.url,s="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case S.DASH_SEP:case S.DASH_ONDEMAND:case S.DASH_WEBM:case S.DASH_WEBM_AV1:{const d=t[e];P(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case S.DASH_LIVE_CMAF:{const d=t[e];P(d),i=d.url,s="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case S.HLS_LIVE:case S.HLS_LIVE_CMAF:{const d=t[e];P(d),i=Ye(d.url),s="application/x-mpegurl",r=chrome.cast.media.StreamType.LIVE;break}case S.DASH:case S.DASH_LIVE:case S.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:d,thrown:h}),h}case S.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=r,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return w(o)&&(n.metadata.title=o),w(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===H.Applying||i.state===H.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,r)=>{this.loadMediaTimeoutSubscription.add(Es(Ri).subscribe(()=>r(`timeout(${Ri})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:r,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!t){if(s?.to!==l.PAUSED&&r.state===H.Requested&&e!==V.STOPPED){this.seek(r.position/1e3);return}switch(i){case l.READY:{switch(e){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}case l.PLAYING:{switch(e){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}case l.PAUSED:{switch(e){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:M(e)}break}default:M(i)}}}}var Os=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,r=s.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>r(n),t&&i&&e?.()}}},!0)},Fs=a=>{const e=new m(1/0),t=new x,i=new m(void 0),s=new m(void 0);let r=NaN,n=!1;const o=()=>{r=Date.now(),n=!1},c=h=>{const u=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(b=>b.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const b=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),v=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??b*1e3??NaN;w(v)&&!isNaN(v)&&e.next(v)}const p=u["x-delivery-type"]??Ot.HTTP1,f={1:!0,0:!1}[u["x-reused"]]??void 0;i.next(p),s.next(f)},d=h=>{h.readyState>=2&&!n&&(n=!0,t.next(Date.now()-r))};return a.extend("XHRLoader",function(){const{parent:h}=this,u=h.load.bind(h);return{load:function(p){if(p.request.type==="MPD"){const f=p.onload,b=p.progress;p.onload=function(...E){return c(this),f(...E)},p.progress=function(...E){return d(this),b(...E)},o()}return u(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},yt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Vs=a=>a.extend("RequestModifier",()=>({modifyRequestURL:yt}),!0),Us=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,r]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${s}-${r}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Ne=(a,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:r}={})=>{const n=a.getState(),o=e(),c=J(s),d=new te;return s&&d.add(s.subscribe(h=>{const u=a.getState();i(h,u)&&a.setState(h)},r)),i(o,n)||(t(n),c&&a.setState(n)),d.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),c&&a.setState(h.to)},r)),d},ft=(a,e,t)=>Ne(e,()=>a.loop,i=>{w(i)&&(a.loop=i)},{onError:t}),Xe=(a,e,t,i)=>Ne(e,()=>({muted:a.muted,volume:a.volume}),s=>{w(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,r)=>s===r||s?.muted===r?.muted&&s?.volume===r?.volume,changed$:t,onError:i}),nt=(a,e,t,i)=>Ne(e,()=>a.playbackRate,s=>{w(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),Hs=a=>["__",a.language,a.label].join("|"),Ys=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class Ge{available$=new x;current$=new m(void 0);error$=new x;video;cueSettings;subscription=new te;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=r=>{this.error$.next({id:"TextTracksManager",category:C.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ne(t.internalTextTracks,()=>Object.values(this.internalTracks),r=>{w(r)&&this.setInternal(r)},{equal:(r,n)=>w(r)&&w(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(y(r=>r.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(Ne(t.externalTextTracks,()=>Object.values(this.externalTracks),r=>{w(r)&&this.setExternal(r)},{equal:(r,n)=>w(r)&&w(n)&&r.length===n.length&&r.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(y(r=>r.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(Ne(t.currentTextTrack,()=>{if(this.video)return;const r=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return r&&this.htmlTextTrackToITextTrack(r).id},r=>this.select(r),{changed$:this.current$,onError:s})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(L(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(B(L(e,"addtrack"),L(e,"removetrack"),Ee(["init"])).pipe(y(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ce((i,s)=>i.length===s.length&&i.every(({id:r},n)=>r===s[n].id))).subscribe(this.available$)),this.subscription.add(B(L(e,"change"),Ee(["init"])).pipe(y(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),y(i=>i&&this.htmlTextTrackToITextTrack(i).id),ce()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(L(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(L(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;w(t.align)&&(s.align=t.align),w(t.position)&&(s.position=t.position),w(t.size)&&(s.size=t.size),w(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ge.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Hs(e),r=this.externalTracks.has(s),n=s.includes("auto");return r?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(s)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:s,isAuto:r})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===r)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(J(e)||!Ys(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const ki=a=>{a.removeAttribute("src"),a.load()},Gs=a=>{try{a.pause(),a.playbackRate=0,ki(a),a.remove()}catch(e){console.error(e)}};class qs{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 bi=window.WeakMap?new WeakMap:new qs,Ke=a=>{let e=a.querySelector("video");const t=!!e;return e?ki(e):(e=document.createElement("video"),a.appendChild(e)),bi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ze=a=>{const e=bi.get(a);bi.delete(a),e?ki(a):Gs(a)};class oi{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 is=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ci=a=>{const e=is(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},zs=a=>{const e=is(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ti=3;class Ws{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const r=this._source.buffered.end(t);s>e&&s-e<Ti&&(s=e),this._buffer.push({from:s,to:r,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ti))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:r})=>{const n=s>=e&&s<t,o=r>=e&&r<t;n&&o||(n?i(t,r):o?i(s,e):s<e&&r>t?(i(t,r),i(s,e)):i(s,r))})}destroy(){this._buffer=[]}}var ss=(a,e,t=Ti)=>{let i=0,s=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let c=r-1;c>=0;c--)a.end(c)+t>=i&&(i=a.start(c));for(let c=r+1;c<a.length;c++)a.start(c)-t<=s&&(s=a.end(c))}}return{from:i,to:s}};const et=a=>{const e=g=>L(a,g).pipe(Tt(void 0)),i=B(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>L(a,g))).pipe(y(g=>g.type==="ended"?a.readyState<2:a.readyState<3),ce()),s=B(L(a,"progress"),L(a,"timeupdate")).pipe(y(()=>ss(a.buffered,a.currentTime))),n=$i().browser===es.Safari?De({play:e("play").pipe(le()),playing:e("playing")}).pipe(Tt(void 0)):e("playing"),o=L(a,"volumechange").pipe(y(()=>({muted:a.muted,volume:a.volume}))),c=L(a,"ratechange").pipe(y(()=>a.playbackRate)),d=L(a,"error").pipe(K(()=>!!(a.error||a.played.length)),y(()=>{const g=a.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=L(a,"timeupdate").pipe(y(()=>a.currentTime)),u=new x,p=.3;let f;h.subscribe(g=>{a.loop&&w(f)&&w(g)&&f>=a.duration-p&&g<=p&&u.next(f),f=g});const b=L(a,"enterpictureinpicture"),E=L(a,"leavepictureinpicture"),v=new m(zs(a));b.subscribe(()=>v.next(!0)),E.subscribe(()=>v.next(!1));const R=new m(Ci(a));return L(a,"fullscreenchange").pipe(y(()=>Ci(a))).subscribe(R),{playing$:n,pause$:e("pause").pipe(K(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:L(a,"durationchange").pipe(y(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:c,inPiP$:v,inFullscreen$:R}},Ai=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let wi=!1,je={};const Qs=a=>{wi=a},js=()=>{je={}},Js=a=>{a(je)},zt=(a,e)=>{wi&&(je.meta=je.meta??{},je.meta[a]=e)};class Ve{name;constructor(e){this.name=e}next(e){if(!wi)return;je.series=je.series??{};const t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}}var ht;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(ht||(ht={}));const Xs=new Ve("best_bitrate"),Ks=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Zs{last;history={};recordSelection(e){this.history[e.id]=ue()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const $t=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d,droppedVideoMaxQualityLimit:h,abrLogger:u})=>{const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},b=f&&pt(f),E=i.considerPlaybackRate&&w(o)?o:1,v=a.filter(A=>!Nt(A.quality)).sort((A,F)=>It(A.quality,F.quality)?-1:1),R=v.at(-1)?.quality,N=v.at(0)?.quality,g=J(s)||w(s.min)&&w(s.max)&&Jt(s.max,s.min)||w(s.min)&&N&&It(s.min,N)||w(s.max)&&R&&Jt(s.max,R),$=E*Ks(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},W=v.filter(A=>(b?Jt(A.quality,b):!0)?(w(t)&&isFinite(t)&&w(A.bitrate)?t-r>=A.bitrate*$:!0)?i.lazyQualitySwitch&&w(i.minBufferToSwitchUp)&&c&&!Nt(c.quality)&&(n??0)<i.minBufferToSwitchUp&&It(A.quality,c.quality)?(k[A.quality]=ht.Buffer,!1):!!h&&Si(A.quality,h)?(k[A.quality]=ht.DroppedFramesLimit,!1):g||(J(s.max)||ts(A.quality,s.max))&&(J(s.min)||Si(A.quality,s.min))?!0:(k[A.quality]=ht.FitsQualityLimits,!1):(k[A.quality]=ht.FitsThroughput,!1):(k[A.quality]=ht.FitsContainer,!1))[0];W&&W.bitrate&&Xs.next(W.bitrate);const G=W??v[Math.ceil((v.length-1)/2)]??a[0];G.quality!==d?.last?.quality&&u({message:`
7
+ [available tracks] ${a.map(A=>A.quality).join(", ")}
8
8
 
9
9
  [limit params]
10
10
  containerQualityLimit: ${b},
11
11
  throughput: ${t},
12
12
  reserve: ${r},
13
- bitrateFactor: ${E},
13
+ bitrateFactor: ${$},
14
14
  forwardBufferHealth: ${n},
15
15
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
16
16
  droppedVideoMaxQualityLimit: ${h},
17
- limitsAreInvalid: ${m},
17
+ limitsAreInvalid: ${g},
18
18
  maxQualityLimit: ${s?.max},
19
19
  minQualityLimit: ${s?.min},
20
20
 
21
21
  [limited tracks]
22
- ${Object.entries(k).map(([P,K])=>`${P}: ${K}`).join(`
22
+ ${Object.entries(k).map(([A,F])=>`${A}: ${F}`).join(`
23
23
  `)||"All tracks are available"}
24
24
 
25
- [best track] ${Q?.quality}
26
- [selected track] ${B?.quality}
27
- `});const N=B&&d&&d.history[B.id]&&re()-d.history[B.id]<=i.trackCooldown&&(!d.last||B.id!==d.last.id);if(B?.id&&d&&!N&&d.recordSelection(B),N&&d?.last){const P=d.last;return d?.recordSwitch(P),u({message:`
28
- [last selected] ${P?.quality}
29
- `}),P}return d?.recordSwitch(B),B};var Ae=a=>new URL(a).hostname;const ra=300,si=(a,e=ra)=>new hi(t=>{const{width:i,height:s}=a.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const r=new ResizeObserver(Cs(n=>{const o=n[0];if(!o)return;let c,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,c=o.contentBoxSize[0].inlineSize):o.contentRect&&(c=o.contentRect.width,d=o.contentRect.height),A(c)&&A(d)&&t.next({width:c,height:d})},e));return r.observe(a),()=>r.disconnect()});class li{onDroopedVideoFramesLimit$=new L;subscription=new te;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new L;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=ii(this.droppedFramesChecker.checkTime).pipe(J(()=>this.playing),J(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Be(this.droppedFramesChecker.checkTime)),i=M(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Ut(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,s=t-this.prevDroppedVideoFrames,r=1-(i-s)/i;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&Nt(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)};onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){const t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[s])=>Zt(i,s)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Ct={};var z;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const pe=(a,e)=>new hi(t=>{const i=s=>t.next(s);return a.on(e,i),()=>a.off(e,i)});class Fi{subscription=new te;videoState=new oe(z.DOWNLOADING_LIB);video;player;params;textTracksManager=new je;droppedFramesManager=new li;videoTracks$=new f([]);frameRatesByFrameHeight={};isLive$=new f(void 0);maxSeekBackTime$=new f(1/0);availableFrom$=new f(void 0);elementSize$=new f(void 0);liveOffset=new ui;constructor(e){this.video=et(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:R.NETWORK,message:`Dash.js failed to load: ${s?.toString?.()}`,thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Ct.MediaPlayer=s.MediaPlayer,Ct.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){w(Ct.MediaPlayer,"dashjs not loaded"),w(Ct.Debug,"dashjs not loaded"),this.player=Ct.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?Ri(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&qs(this.player),Ys(this.player),this.params.tuning.requestQuick&&zs(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:R.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,E)=>this.subscription.add(m.subscribe(E,i));s(si(this.video),this.elementSize$),s(pe(this.player,"error").pipe(v(m=>{const E=typeof m.error=="object"?m.error.code:m.error,k=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${E}`,message:k}})),e.error$),s(pe(this.player,"playbackError").pipe(v(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const r=pe(this.player,"qualityChangeRendered").pipe(J(({mediaType:m})=>m==="video"),v(({newQuality:m})=>this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===m)?.track));r.pipe(J(A)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(J(({to:m})=>m===z.STREAM_INITIALIZED),le()).subscribe(()=>{this.subscription.add(Ue(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===m)?.track?.id},m=>{if(j(m))return;const E=this.videoTracks$.getValue().find(({track:k})=>k.id===m)?.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:r.pipe(v(m=>m?.id)),onError:i}))},i)),this.subscription.add(Ue(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),s(pe(this.player,"bufferStateChanged").pipe(J(({mediaType:m})=>m==="video"),v(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(pe(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:E}})=>{const k=this.player.getDashMetrics(),F=k.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),Q=k.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??Ht.HTTP1,B={1:!0,0:!1}[F]??void 0;this.params.output.httpConnectionType$.next(Q),this.params.output.httpConnectionReused$.next(B),e.hostname$.next(Ae(E))}),s(pe(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:E,availableFrom:k}}})=>{this.isLive$.next(E),this.availableFrom$.next(k.getTime()),E||e.duration$.next(m);const F=[],Q=this.player.getQualityFor("video");let B;for(const N of this.player.getBitrateInfoListFor("video")){const P=N.qualityIndex.toString(10),K=St(N),q=N.bitrate/1e3,ie={width:N.width,height:N.height},be=this.frameRatesByFrameHeight[N.height];if(K){const xe={id:P,quality:K,bitrate:q,size:ie,fps:be};F.push({track:xe,bitrateInfo:N}),N.qualityIndex===Q&&(B=xe)}}this.videoTracks$.next(F),e.availableVideoTracks$.next(F.map(({track:N})=>N)),B&&e.currentVideoTrack$.next(B),this.videoState.setState(z.STREAM_INITIALIZED),this.videoState.startTransitionTo(z.READY)}),s(pe(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const E=m.requestEndDate.getTime()-m.firstByteDate.getTime(),k=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(k,E)}),s(M(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),E=Lt(this.videoTracks$.getValue().map(({track:Q})=>Q),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),k=t.autoVideoTrackLimits.getTransition();k&&e.autoVideoTrackLimits$.next(k.to);const F=this.videoTracks$.getValue().find(({track:Q})=>Q===E);F?.bitrateInfo&&this.player.setQualityFor("video",F?.bitrateInfo.qualityIndex,!1)}),s($e({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(J(A))}).pipe(J(({isLive:m})=>m),v(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=pe(this.player,"playbackTimeUpdated").pipe(v(({time:m})=>m??0));s($e({availableFrom:this.availableFrom$.pipe(J(A)),currentTime:n}),({availableFrom:m,currentTime:E})=>this.params.output.liveTime$.next(m+E*1e3)),s(n.pipe(J(()=>this.isLive$.getValue()===!1)),e.position$),s(pe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(pe(this.player,"playbackEnded"),e.endedEvent$),s(pe(this.player,"playbackProgress").pipe(v(()=>cs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(pe(this.player,"playbackPlaying"),()=>{this.videoState.setState(z.PLAYING),D(t.playbackState,l.PLAYING)}),s(pe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(pe(this.player,"playbackPaused"),()=>{this.videoState.setState(z.PAUSED),D(t.playbackState,l.PAUSED)}),s(pe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY)}),s(this.isLive$,e.isLive$),s(si(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(Be(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=Gs(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(le()),e.firstBytesEvent$),s(pe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s($e({isLive:this.isLive$,isShort:e.duration$.pipe(v(m=>m<60))}),({isLive:m,isShort:E})=>{const k=!m&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:k}}})}),s(n.pipe(J(m=>m>this.params.tuning.insufficientBufferRuleMargin),le()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(pe(this.player,"manifestLoaded").pipe(le()).subscribe(()=>{this.subscription.add(pe(this.player,"playbackPlaying").pipe(le(),wt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(pe(this.player,"manifestLoaded"),m=>{if(m.data?.Period?.AdaptationSet){const E=[];for(const k of m.data?.Period?.AdaptationSet)if(k.contentType==="text"){const F=k.Representation?.id,Q=new URL(k.Representation?.BaseURL,m.data?.baseUri).toString(),B="internal",N=k.lang;E.push({id:F,url:Q,type:B,language:N})}t.internalTextTracks.startTransitionTo(E)}}),this.subscription.add(bt(this.video,t.isLooped,i));const{volumeState$:p,looped$:S,playbackRateState$:b,inPiP$:$,inFullscreen$:T,pause$:_,playing$:G}=it(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:G,pause$:_,tracks$:this.videoTracks$.pipe(v(m=>m.map(({track:E})=>E)))}),this.subscription.add(Ze(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(S.subscribe(e.loopedEvent$)),this.subscription.add(ct(this.video,t.playbackRate,b,i)),this.subscription.add($.subscribe(e.inPiP$)),this.subscription.add(T.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(z.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(z.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=Qe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,fe.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(z.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(z.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===z.DOWNLOADING_LIB||e===z.STREAM_INITIALIZED))switch(i?.to!==l.PAUSED&&s.state===Y.Requested&&e!==z.STOPPED&&t!==l.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case l.STOPPED:{switch(e){case z.STOPPED:break;case z.PLAYING:case z.PAUSED:case z.READY:this.stop();break;default:O(e)}break}case l.READY:{switch(e){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:O(e)}break}case l.PLAYING:{switch(e){case z.PLAYING:break;case z.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case z.READY:this.play();break;case z.STOPPED:this.prepare();break;default:O(e)}break}case l.PAUSED:{switch(e){case z.PLAYING:this.pause(),this.liveOffset.pause();break;case z.PAUSED:break;case z.READY:this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED);break;case z.STOPPED:this.prepare();break;default:O(e)}break}default:O(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}tt(this.video),this.params.output.element$.next(void 0)}}var Gt=a=>{switch(a){case"mobile":return Re.Q_144P;case"lowest":return Re.Q_240P;case"low":return Re.Q_360P;case"sd":case"medium":return Re.Q_480P;case"hd":case"high":return Re.Q_720P;case"fullhd":case"full":return Re.Q_1080P;case"quadhd":case"quad":return Re.Q_1440P;case"ultrahd":case"ultra":return Re.Q_2160P}};const Vi=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var ht=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!Vi(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return Vi(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function Te(){return re()}function hs(a){return Te()-a}function Ui(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,c=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return c&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function na(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function ei(a,e,t,i){const s=window.XMLHttpRequest;let r,n,o,c=!1,d=0,h,u,p=!1,S="arraybuffer",b=7e3,$=2e3,T=()=>{if(c)return;w(h);const q=hs(h);let ie;if(q<$){ie=$-q,setTimeout(T,ie);return}$*=2,$>b&&($=b),n&&n.abort(),n=new s,F()};const _=q=>(r=q,K),G=q=>(u=q,K),m=()=>(S="json",K),E=()=>{if(!c){if(--d>=0){T(),i&&i();return}c=!0,u&&u(),t&&t()}},k=q=>(p=q,K),F=()=>{h=Te(),n=new s,n.open("get",a);let q=0,ie,be=0;const xe=()=>(w(h),Math.max(h,Math.max(ie||0,be||0)));if(r&&n.addEventListener("progress",I=>{const ee=Te();r.updateChunk&&I.loaded>q&&(r.updateChunk(xe(),I.loaded-q),q=I.loaded,ie=ee)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(c)return;w(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&r){const ee=n.response.byteLength-q;ee&&r.updateChunk&&r.updateChunk(xe(),ee)}u&&u(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),p){const I=()=>{w(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(be=Te(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=S,n.send(),K},K={withBitrateReporting:_,withParallel:k,withJSONResponse:m,withRetryCount:q=>(d=q,K),withRetryInterval:(q,ie)=>(A(q)&&($=q),A(ie)&&(b=ie),K),withTimeout:q=>(o=q,K),withFinally:G,send:F,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return K}const oa=100,da=2e3,ca=500;let ha=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-ca;if(t-e>da){let i=0,s=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)i+=r.end-r.start,s+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;i+=n;const c=r.bytes*n/o;s+=c,r.start=t,r.bytes-=c}}}if(s>0&&i>0){const r=s*8/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>oa&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class ua{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=Te(),s=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},r=c=>{e._complete=1,e._responseData=c,e._downloadTime=Te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ei(t,r,()=>s("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,s){const r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=r._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),r._finallyCB&&r._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(r,e)}},r._cb=t,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=n=>(r._finallyCB=n,r),r}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Xt=1e4,Kt=3,la=300,pa=2e3,fa=6e4,ma=10,ga=1,Sa=500;class ba{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new ha(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ui(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Ui(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,r;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)r=this.manifest[o],!(this.maxAutoQuality&&r.video.height>this.maxAutoQuality)&&(r.bitrate<e&&n>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||A(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{na(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ua(Kt,Xt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let r=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const E=r&&(!h||h===this.rep);return E||t("Not running!"),E},p=(E,k,F)=>{c&&c.abort(),c=ei(this.urlResolver.resolve(E,!1),k,F,()=>this._retryCallback()).withTimeout(Xt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Kt).withFinally(()=>{c=null}).send()},S=(E,k,F)=>{w(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),k,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=E=>{const k=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${k}=>${E}`),i.playbackRate=E)},$=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const F=Te()-1e4;let Q=0;for(let N=0;N<this.bufferStates.length;N++){const P=this.bufferStates[N];E=Math.min(E,P.buf),P.ts<F&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${E} drop=${Q} jitter=${this.sourceJitter}`);let B=E-ga;this.sourceJitter>=0?B-=this.sourceJitter/2:this.sourceJitter-=1,B>3?b(1.15):B>1?b(1.1):B>.3?b(1.05):b(1)}},_=E=>{let k;const F=()=>k&&k.start?k.start.length:0,Q=I=>k.start[I]/1e3,B=I=>k.dur[I]/1e3,N=I=>k.fragIndex+I,P=(I,ee)=>({chunkIdx:N(I),startTS:Q(I),dur:B(I),discontinuity:ee}),K=()=>{let I=0;if(k&&k.dur){let ee=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=ee;this.sourceJitter>1&&(me+=this.sourceJitter-1);let ke=k.dur.length-1;for(;ke>=0&&(me-=k.dur[ke],!(me<=0));--ke);I=Math.min(ke,k.dur.length-1-ue),I=Math.max(I,0)}return P(I,!0)},q=I=>{const ee=F();if(!(ee<=0)){if(A(I)){for(let ue=0;ue<ee;ue++)if(Q(ue)>I)return P(ue)}return K()}},ie=I=>{const ee=F(),ue=I?I.chunkIdx+1:0,me=ue-k.fragIndex;if(!(ee<=0)){if(!I||me<0||me-ee>ma)return t(`Resync: offset=${me} bChunks=${ee} chunk=`+JSON.stringify(I)),K();if(!(me>=ee))return P(ue-k.fragIndex,!1)}},be=(I,ee,ue)=>{d&&d.abort(),d=ei(this.urlResolver.resolve(I,!0,this.lowLatency),ee,ue,()=>this._retryCallback()).withTimeout(Xt).withRetryCount(Kt).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,ee)=>{be(E,ue=>{if(!u())return;k=ue;const me=!!k.lowLatency;me!==this.lowLatency&&$(me);let ke=0;for(let at=0;at<k.dur.length;++at)ke+=k.dur[at];ke>0&&(w(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ke/k.dur.length)),s({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,I(q(ee))},()=>this._handleNetworkError())},nextChunk:ie}},G=()=>{r=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),w(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:E=>{const{videoElement:k,logger:F}=this.params;let Q=_(e.jidxUrl),B,N,P,K,q=0,ie,be,xe;const I=()=>{ie&&(clearTimeout(ie),ie=void 0);const Z=Math.max(Sa,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ve=q+Z,Le=Te(),we=Math.min(1e4,ve-Le);q=Le;const lt=()=>{d||u()&&Q.seek(()=>{u()&&(q=Te(),ee(),I())})};we>0?ie=window.setTimeout(()=>{this.paused?I():lt()},we):lt()},ee=()=>{let Z;for(;Z=Q.nextChunk(K);)K=Z,fi(Z);const ve=Q.nextChunk(P);if(ve){if(P&&ve.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?I():(G(),this._initPlayerWith(e));return}at(ve)}else I()},ue=(Z,ve)=>{if(!u()||!this.sourceBuffer)return;let Le,we,lt;const Oe=Je=>{window.setTimeout(()=>{u()&&ue(Z,ve)},Je)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),Oe(100);else{const Je=Te(),_e=k.currentTime;!this.paused&&k.buffered.length>1&&be===_e&&Je-xe>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),be!==_e&&(be=_e,xe=Je);const Ne=this._getBufferSizeSec();if(Ne>30)F(`Buffered ${Ne} seconds; delaying appendBuffer`),Oe(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:Je,buf:Ne}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ve&&ve()}catch(yt){if(yt.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),lt=this.sourceBuffer.buffered.length,lt!==0&&(Le=this.sourceBuffer.buffered.start(0),we=_e,we-Le>4&&this.sourceBuffer.remove(Le,we-3)),Oe(1e3);else throw yt}}},me=()=>{N&&B&&(F([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(P)]),ue(N,function(){N=null,ee()}))},ke=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),at=Z=>{u()&&S(ke(Z),(ve,Le)=>{if(u()){if(Le/=1e3,N=ve,P=Z,n=Z.startTS,Le){const we=Math.min(10,Z.dur/Le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}me()}},()=>this._handleNetworkError())},fi=Z=>{u()&&(w(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ke(Z),!1)))},zt=Z=>{u()&&(e.cachedHeader=Z,ue(Z,()=>{B=!0,me()}))};r=!0,Q.seek(Z=>{if(u()){if(q=Te(),!Z){I();return}K=Z,!j(E)||Z.startTS>E?at(Z):(P=Z,ee())}},E),e.cachedHeader?zt(e.cachedHeader):p(e.headerUrl,zt,()=>this._handleNetworkError())},stop:G,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),A(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,w(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return A(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let p,S,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(S=this._getBufferSizeSec(),b=u/this.bitrate,S>10&&b>.8||S>15&&b>.5||S>20&&b>.3)){e(`Not switching: buffer=${Math.floor(S)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}p=this._selectQuality(u),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${u}`)},r=(()=>({updateChunk:(p,S)=>{const b=Te();if(this.chunkRateEstimator.addInterval(p,b,S)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:S,duration:b-p,speed:T}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=r.get();if(u&&o&&this.autoQuality){if(c&&u>o&&hs(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,p)=>{const S=r.updateChunk(u,p);return S&&d(),S},notifySwitch:u=>{const p=Te();u<o&&(n=p),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=ei(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Xt).withRetryCount(Kt).withRetryInterval(la,pa).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ht(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,r=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&s.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=d,o.push(c))}),o.sort(function(c,d){return c.video&&d.video?d.video.height-c.video.height:d.bitrate-c.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=r(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},fa))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var H;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(H||(H={}));const ya=[H.PAUSED,H.PLAYING,H.READY],Ta=[H.PAUSED,H.PLAYING,H.READY];class va{subscription=new te;video;videoState=new oe(H.STOPPED);dash;representations$=new f([]);textTracksManager=new je;droppedFramesManager=new li;maxSeekBackTime$=new f(1/0);zeroTime$=new f(void 0);liveOffset=new ui;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:R.WTF,message:"DashLiveProvider internal logic error",thrown:s})};M(this.videoState.stateChangeStarted$.pipe(v(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(s)}`})}),this.video=et(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=it(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(v(s=>s.map(({track:r})=>r)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(he(),v(s=>-s/1e3)).subscribe(this.params.output.duration$)).add($e({zeroTime:this.zeroTime$.pipe(J(A)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:r})=>this.params.output.liveTime$.next(s+r*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Ze(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ct(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const r=s&&xs(s);this.dash.setMaxAutoQuality(r),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case H.MANIFEST_READY:case H.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return O(s.to)}},t)).add(M(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,De(["init"])).pipe(Be(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),tt(this.video)}createLiveDashPlayer(){const e=new ba({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&A(t)?t:Lt(e.map(({track:c})=>c),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id,r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((r&&s||s!==n)&&this.setVideoTrack(s),o&&this.setAutoQuality(i),r||o||s!==n){const c=e.find(({track:d})=>d.id===s)?.representation;w(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e)?.representation;w(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===H.PAUSED,r=-e,n=r<=this.maxSeekBackTime$.getValue()?r:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Qe(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:R.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const r=s.name??s.index.toString(10),n=Gt(s.name)??St(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:r,quality:n,bitrate:o,size:c};i.push({track:d,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),A(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ta.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==l.PAUSED&&r.state===Y.Requested&&ya.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Qe(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(i===l.PAUSED)this.videoState.setState(H.PAUSED);else if(i===l.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const c=s?.from;c&&c===l.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)})}return;case H.PLAYING:i===l.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:i===l.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(H.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return O(e)}}}var us=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?Ht.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},dt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,r=a.end(i)*1e3;s<=e&&e<=r&&(t=r)}return Math.max(t-e,0)};const Ea=a=>{const e=document.createElement("a");return e.href=a,e.origin},$a=a=>{const e=document.createElement("a");return e.href=a,e.host};class ls{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,r,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(this._xhr){if(this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(i=>i.split(":").map(s=>s.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace($a(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",t,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class ai{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let r=0;for(let n=0,o=s.length;n<o;n++)r+=s.end(n)-s.start(n);r&&(this._maxBufferDuration=Math.round(r))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,r,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,p=0;const S=$=>{s(ai._str2ua($.substr(c))),c=$.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=Pt(b)),this._lastXhr=new ls(b,e.failoverHosts,$=>{this._lastXhr=void 0,S($);const T=Date.now()-d;this._params.onBandwidthChange({size:$.length,duration:T,speed:8*$.length/(T/1e3)}),this._onDashCallback("loading",{size:$.length,done:!0}),r?.()},$=>{if($.length-c>o&&S($),u===0){u=Date.now();return}p=$.length-h;const T=Date.now()-u;p>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:p,duration:T,speed:8*p/(T/1e3)}),p=0,h=$.length,u=Date.now()),this._onDashCallback("loading",{size:$.length,done:!1})},n,($,T,_)=>this._params.onError($,T,_))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=ai._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Aa{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},s=t.exec(e),r=s?.[1]==="-"?-1:1,n={years:i(s?.[2],r),months:i(s?.[3],r),weeks:i(s?.[4],r),days:i(s?.[5],r),hours:i(s?.[6],r),minutes:i(s?.[7],r),seconds:i(s?.[8],r)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Pt(i)),new ls(i,t,s=>{this.attachManifest(s,t,Ea(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,r,n)=>this._params.onError(s,r,n))}attachManifest(e,t,i){const r=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,h)=>{const u=d.attributes.getNamedItem(h);return u?u.value:null};this._duration=this._parseDurationFromISO8601(String(n(r,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(r.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),p=h&&h.getElementsByTagName("Initialization")[0],S=p&&n(p,"range").split("-");if(!S||!u){const m=d.parentElement;if(m?.getAttribute("contentType")==="text"){const E=d.getAttribute("id")??void 0,k=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,F=m.getAttribute("lang")??void 0;k&&c.push({id:E,url:k,language:F})}return}const b=.1,$=Number(d.attributes.getNamedItem("bandwidth")?.value),T=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let _;const G=d.attributes.getNamedItem("frameRate")?.value??void 0;_=G?Ri(G):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:$,baseURL:T,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(S[0]),initTo:Number(S[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:_,bufferSize:b*$/8,bufferLength:b,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:h,url:u})=>{const p=document.createElement("track");u&&p.setAttribute("src",u),d&&p.setAttribute("id",d),h&&p.setAttribute("srclang",h),this._video.appendChild(p)}),this._representations.sort((d,h)=>h.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:c})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let r=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,r);const n=new DataView(s.buffer);r+=12;const o=n.getUint32(r+4,!1);r+=8;let c=n.getUint32(r,!1),d=n.getUint32(r+4,!1)+(e.indexTo+1);r+=8;const h=n.getUint16(r+2,!1);r+=4,e.refs=[];for(let p=0;p<h;p+=1){const S=d+(n.getUint32(r,!1)&2147483647),b=c+n.getUint32(r+4,!1);r+=12,e.refs.push({fromTime:c/o,toTime:b/o,fromOffset:d,toOffset:S-1}),d=S,c=b}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let s,r;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const S=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),S)}const h=this._appendVector[String(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const S=this._buffer.getByTime(this._video.currentTime);if(!S){this._onDashCallback("buffering");return}u=S.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),r!==S.to&&(r=S.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(S);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},u*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},c=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ai({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",c),i.removeEventListener("webkitsourceopen",c)};i.addEventListener("sourceopen",c,!1),i.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const r=this._findRef(t);if(r){if(i){this._isLastRef(r)&&t>=r.toTime&&(t=r.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:r.fromTime}this._appendVector[String(r.fromTime)]=e,this._stream.load(e,r.fromOffset,r.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=r.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const r=.1;if(s.toTime<i.to+r){const n=this._findRef(s.toTime);n&&n.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,n.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||j(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let i;for(let s=0;s<t.length;s++){const r=t[s];if(r.fromTime<=e&&r.toTime>e)return r;r.fromTime>e&&(!i||r.fromTime<i.fromTime)&&(i=r)}if(!i){const s=t[t.length-1];if(e>s.toTime)return s}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>i&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var W;(function(a){a.STOPPED="stopped",a.MANIFEST_LOADED="manifest-loaded",a.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",a.METADATA_LOADED="metadata-loaded",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(W||(W={}));const ka=[W.PAUSED,W.PLAYING];class wa{videoState=new oe(W.STOPPED);subscription=new te;video;buffer;dash;representations$=new f([]);currentRepresentation$=new f(void 0);params;textTracksManager=new je;droppedFramesManager=new li;elementSize$=new f(void 0);dashLiteEvents={idxRequestPing$:new L,responseHeaders$:new L,manifestReady$:new L,representationPlay$:new L,error$:new L};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),M(this.videoState.stateChangeStarted$.pipe(v(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=et(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ks(this.video),this.dash=new Aa({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:s,category:R.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:R.WTF,message:"DashProvider internal logic error",thrown:o})},s=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},r=it(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(r.seeking$.subscribe(()=>{j(this.params.desiredState.seekState.getState().state!==Y.Applying)&&(this.videoState.getState()===W.PLAYING||this.videoState.getState()===W.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ze(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ct(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(v(o=>o.map(({track:c})=>c)))}),n(si(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)})).add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING)},i)).add(r.loadedMetadata$.subscribe(()=>{this.videoState.setState(W.METADATA_LOADED)},i)).add(r.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(v(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:R.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(M(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,C(this.video,"progress")).pipe(v(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let b;if(!S&&A(h))b=h;else{const $=dt(this.video.buffered,this.video.currentTime*1e3),T=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,_=Math.min($/T,1);b=Lt(c.map(({track:m})=>m),{container:p,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:_,playbackRate:this.video.playbackRate,current:c.find(({representation:m})=>m===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const G=t.autoVideoTrackLimits.getTransition();G&&e.autoVideoTrackLimits$.next(G.to)}return A(b)?c.find(({track:$})=>$.id===b)?.representation:void 0}),he()).subscribe(this.currentRepresentation$,i)).add($e({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(J(o=>o.to===W.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(J(A))}).pipe(le()).subscribe(()=>this.videoState.setState(W.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(J(A),he((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=dt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!s())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(Ae(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=us(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(le(),wt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(J(A)).subscribe(this.handleRepresentationPlay,i)).add(M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(Be(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return O(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const r=s.name??s.id??s.height.toString(10),n=(s.name&&Gt(s.name))??St(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:r,quality:n,bitrate:o,size:c,fps:d};i.push({track:h,representation:s})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),t?.length>0){const s=[];for(const r of t){const n=r.id||`${r.language}_${Date.now()}`;s.push({id:n,type:"internal",url:r.url||"",language:r.language,isAuto:r.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(W.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return w(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(s?.to!==l.PAUSED&&r.state===Y.Requested&&ka.includes(e)&&this.seek(r.position,r.forcePrecise),e){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_LOADED),this.prepare();return;case W.MANIFEST_LOADED:this.videoState.startTransitionTo(W.INITIAL_REPRESENTATION_SELECTED);return;case W.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(W.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case W.METADATA_LOADED:this.videoState.startTransitionTo(W.READY),this.dash.updateRefsForCurrentTime();return;case W.READY:i===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(W.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case W.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return O(e)}}}var Se;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Se||(Se={}));var Ge;(function(a){a[a.ActiveLowLatency=0]="ActiveLowLatency",a[a.LiveWithTargetOffset=1]="LiveWithTargetOffset",a[a.LiveForwardBuffering=2]="LiveForwardBuffering",a[a.None=3]="None"})(Ge||(Ge={}));var ri;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ri||(ri={}));var Ie;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Ie||(Ie={}));var U;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(U||(U={}));var Dt;(function(a){a.MP4="mp4",a.WEBM="webm"})(Dt||(Dt={}));var ni;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(ni||(ni={}));var de;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(de||(de={}));var ki=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};let ps=!1;try{ps=Li().browser===ns.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Pa{bufferFull$=new L;error$=new L;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const r={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let i;ps&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:R.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:O(t)}}}var Hi=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class Me{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 fs extends Me{}class Da extends Me{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 xa extends Me{parseChildrenBoxes(){return ut(this.content)}}class La extends Me{parseChildrenBoxes(){return ut(this.content)}}class _a extends Me{data;constructor(e){super(e),this.data=this.content}}class st extends Me{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Ra extends st{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,r=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:r,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class Ca extends Me{parseChildrenBoxes(){return ut(this.content)}}class Ia extends Me{parseChildrenBoxes(){return ut(this.content)}}var gt;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(gt||(gt={}));class Ba extends st{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=gt.MONOSCOPIC;break;case 1:this.stereoMode=gt.TOP_BOTTOM;break;case 2:this.stereoMode=gt.LEFT_RIGHT;break;case 3:this.stereoMode=gt.STEREO_CUSTOM;break;case 4:this.stereoMode=gt.RIGHT_LEFT;break}this.cursor+=1}}class Ma extends st{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Oa extends st{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 Na extends Me{parseChildrenBoxes(){return ut(this.content)}}class Fa extends st{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 Va extends Me{parseChildrenBoxes(){return ut(this.content)}}class Ua extends Me{parseChildrenBoxes(){return ut(this.content)}}class Ha extends st{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Ya extends Me{parseChildrenBoxes(){return ut(this.content)}}class Ga extends st{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 za extends st{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 qa extends st{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 Wa={ftyp:Da,moov:xa,moof:La,mdat:_a,sidx:Ra,trak:Ca,mdia:Na,mfhd:Ha,tkhd:Fa,traf:Ya,tfhd:Ga,tfdt:za,trun:qa,minf:Va,sv3d:Ia,st3d:Ba,prhd:Ma,proj:Ua,equi:Oa,unknown:fs};class Qa{createBox(e,t){const i=Wa[e];return i?new i(t):new fs(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return pi.createBox(i,new DataView(e.buffer,e.byteOffset))}}const pi=new Qa;function Ot(a,e){const t=new Uint8Array(a.buffer),i=e.split("").map(n=>n.charCodeAt(0));let s=a.byteOffset,r=[];for(;s<t.byteLength;){if(t[s]===i[r.length]?r.push(t[s]):r=[],r.length===4){const o=new DataView(a.buffer,s-7,4).getUint32(0);return s-7+o>a.buffer.byteLength?null:pi.createBox(e,new DataView(a.buffer,s-7))}s++}return null}function wi(a,e){const t=[];let i=a.byteOffset;for(;i<a.buffer.byteLength;){const s=Ot(new DataView(a.buffer,i,a.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function ut(a){const e=[];let t=0;for(;t<a.byteLength;){const i=pi.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const ja=new TextDecoder("ascii"),Ja=a=>ja.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Xa=a=>{const e=pi.createFromView(a);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(r=>{if(r.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=r.subsegmentDuration/e.timescale*1e3,o={status:U.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+r.referencedSize-1}};return t+=n,i+=r.referencedSize,o})},Ka=a=>{const e=wi(a,"mdat"),t=wi(a,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],r=i.source.byteOffset,o=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(a.buffer,r,o)},Za=(a,e)=>{const t=wi(a,"traf"),i=t[t.length-1].children.find(c=>c.type==="tfhd"),s=t[t.length-1].children.find(c=>c.type==="tfdt"),r=t[t.length-1].children.find(c=>c.type==="trun");let n=0;return r.sampleDuration.length?n=r.sampleDuration.reduce((c,d)=>c+d,0):n=i.defaultSampleDuration*r.sampleCount,(Number(s.baseMediaDecodeTime)+n)/e*1e3},er=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ot(a,"sv3d")){e.is3dVideo=!0;const i=Ot(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=Ot(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const r=Ot(a,"equi");r&&(e.projectionData.bounds.top=r.projectionBoundsTop,e.projectionData.bounds.right=r.projectionBoundsRight,e.projectionData.bounds.bottom=r.projectionBoundsBottom,e.projectionData.bounds.left=r.projectionBoundsLeft)}return e},tr={validateData:Ja,parseInit:er,getIndexRange:()=>{},parseSegments:Xa,parseFeedableSegmentChunk:Ka,getSegmentEndTime:Za};var y;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(y||(y={}));var x;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(x||(x={}));const Yi={[y.EBML]:{type:x.Master},[y.EBMLVersion]:{type:x.UnsignedInteger},[y.EBMLReadVersion]:{type:x.UnsignedInteger},[y.EBMLMaxIDLength]:{type:x.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:x.UnsignedInteger},[y.DocType]:{type:x.String},[y.DocTypeVersion]:{type:x.UnsignedInteger},[y.DocTypeReadVersion]:{type:x.UnsignedInteger},[y.Void]:{type:x.Binary},[y.Segment]:{type:x.Master},[y.SeekHead]:{type:x.Master},[y.Seek]:{type:x.Master},[y.SeekID]:{type:x.Binary},[y.SeekPosition]:{type:x.UnsignedInteger},[y.Info]:{type:x.Master},[y.TimestampScale]:{type:x.UnsignedInteger},[y.Duration]:{type:x.Float},[y.Tracks]:{type:x.Master},[y.TrackEntry]:{type:x.Master},[y.Video]:{type:x.Master},[y.Projection]:{type:x.Master},[y.ProjectionType]:{type:x.UnsignedInteger},[y.ProjectionPrivate]:{type:x.Master},[y.Chapters]:{type:x.Master},[y.Cluster]:{type:x.Master},[y.Timestamp]:{type:x.UnsignedInteger},[y.SilentTracks]:{type:x.Master},[y.SilentTrackNumber]:{type:x.UnsignedInteger},[y.Position]:{type:x.UnsignedInteger},[y.PrevSize]:{type:x.UnsignedInteger},[y.SimpleBlock]:{type:x.Binary},[y.BlockGroup]:{type:x.Master},[y.EncryptedBlock]:{type:x.Binary},[y.Attachments]:{type:x.Master},[y.Tags]:{type:x.Master},[y.Cues]:{type:x.Master},[y.CuePoint]:{type:x.Master},[y.CueTime]:{type:x.UnsignedInteger},[y.CueTrackPositions]:{type:x.Master},[y.CueTrack]:{type:x.UnsignedInteger},[y.CueClusterPosition]:{type:x.UnsignedInteger},[y.CueRelativePosition]:{type:x.UnsignedInteger},[y.CueDuration]:{type:x.UnsignedInteger},[y.CueBlockNumber]:{type:x.UnsignedInteger},[y.CueCodecState]:{type:x.UnsignedInteger},[y.CueReference]:{type:x.Master},[y.CueRefTime]:{type:x.UnsignedInteger}},ms=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=oi(a,t),s=i in Yi,r=s?Yi[i].type:x.Binary,n=a.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(a.buffer,a.byteOffset+t+1,o-1),d=n&255>>o,h=oi(c),u=d*2**((o-1)*8)+h,p=t+o;let S;return p+u>a.byteLength?S=new DataView(a.buffer,a.byteOffset+p):S=new DataView(a.buffer,a.byteOffset+p,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:r,tagHeaderSize:p,tagSize:p+u,value:S,valueSize:u}},oi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},qe=(a,e)=>{switch(e){case x.SignedInteger:return a.getInt8(0);case x.UnsignedInteger:return oi(a);case x.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case x.String:return new TextDecoder("ascii").decode(a);case x.UTF8:return new TextDecoder("utf-8").decode(a);case x.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case x.Master:return a;case x.Binary:return a;default:O(e)}},xt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=ms(i);if(!e(s))return;s.type===x.Master&&xt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},ir=a=>{if(a.getUint32(0)!==y.EBML)return!1;let e,t,i;const s=ms(a);return xt(s.value,({tag:r,type:n,value:o})=>(r===y.EBMLReadVersion?e=qe(o,n):r===y.DocType?t=qe(o,n):r===y.DocTypeReadVersion&&(i=qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},gs=[y.Info,y.SeekHead,y.Tracks,y.TrackEntry,y.Video,y.Projection,y.ProjectionType,y.ProjectionPrivate,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],sr=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],ar=a=>{let e,t,i,s,r=!1,n=!1,o=!1,c,d,h=!1;const u=0;return xt(a,({tag:p,type:S,value:b,valueSize:$})=>{if(p===y.SeekID){const T=qe(b,S);d=oi(T)}else p!==y.SeekPosition&&(d=void 0);return p===y.Segment?(e=b.byteOffset,t=b.byteOffset+$):p===y.Info?r=!0:p===y.SeekHead?n=!0:p===y.TimestampScale?i=qe(b,S):p===y.Duration?s=qe(b,S):p===y.SeekPosition&&d===y.Cues?c=qe(b,S):p===y.Tracks?xt(b,({tag:T,type:_,value:G})=>T===y.ProjectionType?(h=qe(G,_)===1,!1):!0):r&&n&&gs.includes(p)&&(o=!0),!o}),w(e,"Failed to parse webm Segment start"),w(t,"Failed to parse webm Segment end"),w(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:u,projectionType:ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},rr=a=>{if(j(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},nr=(a,e)=>{let t=!1,i=!1;const s=o=>A(o.time)&&A(o.position),r=[];let n;return xt(a,({tag:o,type:c,value:d})=>{switch(o){case y.Cues:t=!0;break;case y.CuePoint:n&&s(n)&&r.push(n),n={};break;case y.CueTime:n&&(n.time=qe(d,c));break;case y.CueTrackPositions:break;case y.CueClusterPosition:n&&(n.position=qe(d,c));break;default:t&&gs.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&r.push(n),r.map((o,c)=>{const{time:d,position:h}=o,u=r[c+1];return{status:U.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}}})},or=a=>{let e=0,t=!1;try{xt(a,i=>i.tag===y.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):sr.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},dr={validateData:ir,parseInit:ar,getIndexRange:rr,parseSegments:nr,parseFeedableSegmentChunk:or},Gi=a=>{if(!a.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),s=i?.[1]==="-"?-1:1,r={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},At=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,r]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>j(r)?o:j(c)?r:r.padStart(parseInt(c,10),"0"))}return t},cr=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},r=i.children[0],n=r.getElementsByTagName("Period")[0],o=n.children,c=r.getAttribute("type")==="dynamic",d=r.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const p=r.getAttribute("mediaPresentationDuration"),S=n.getAttribute("duration"),$=r.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)u=Gi(p);else if(S){const m=Gi(S);A(m)&&(u=m)}else $&&(u=parseInt($,10));let T=0;const _=r.getAttribute("profiles")?.split(",")??[],G=_.includes(ri.WEBM_AS_IN_FFMPEG)||_.includes(ri.WEBM_AS_IN_SPEC)?Dt.WEBM:Dt.MP4;for(const m of o){const E=m.getAttribute("mimeType"),k=m.getAttribute("codecs"),F=m.getAttribute("contentType")??E?.split("/")[0],Q=m.getAttribute("profiles")?.split(",")??[],B=m.querySelectorAll("Representation"),N=m.querySelector("SegmentTemplate");if(F===Se.TEXT){for(const P of B){const K=P.getAttribute("id")||"",q=m.getAttribute("lang"),ie=P.querySelector("BaseURL")?.textContent?.trim()??"",be=new URL(ie,e).toString();s[Se.TEXT].push({id:K,lang:q,kind:Se.TEXT,url:be})}continue}for(const P of B){const K=P.getAttribute("mimeType")??E,q=P.getAttribute("codecs")??k??"",ie=P.getAttribute("contentType")??K?.split("/")[0]??F,be=m.getAttribute("profiles")?.split(",")??[],xe=parseInt(P.getAttribute("width")??"",10),I=parseInt(P.getAttribute("height")??"",10),ee=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,ue=P.getAttribute("frameRate")??"",me=P.getAttribute("quality")??void 0,ke=ue?Ri(ue):void 0,at=P.getAttribute("id")??(T++).toString(10),fi=ie==="video"?`${I}p`:ie==="audio"?`${ee}Kbps`:q,zt=`${at}@${fi}`,Z=P.querySelector("BaseURL")?.textContent?.trim()??"",ve=new URL(Z,e).toString(),Le=[..._,...Q,...be];let we;const lt=P.querySelector("SegmentBase"),Oe=P.querySelector("SegmentTemplate")??N;if(lt){const _e=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,yt]=_e.split("-").map(Tt=>parseInt(Tt,10)),rt={from:Ne,to:yt},_t=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[mi,qt]=_t?_t.split("-").map(Tt=>parseInt(Tt,10)):[],Rt=_t?{from:mi,to:qt}:void 0;we={type:Ie.BYTE_RANGE,url:ve,initRange:rt,indexRange:Rt}}else if(Oe){const _e={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},Ne=parseInt(Oe.getAttribute("timescale")??"",10),yt=Oe.getAttribute("initialization")??"",rt=Oe.getAttribute("media"),_t=parseInt(Oe.getAttribute("startNumber")??"",10)??1,mi=At(yt,_e);if(!rt)throw new ReferenceError("No media attribute in SegmentTemplate");const qt=Oe.querySelectorAll("SegmentTimeline S")??[],Rt=[];let Tt=0,gi="",Si=0;if(qt.length){let Wt=_t,Fe=0;for(const vt of qt){const He=parseInt(vt.getAttribute("d")??"",10),pt=parseInt(vt.getAttribute("r")??"",10)||0,Qt=parseInt(vt.getAttribute("t")??"",10);Fe=Number.isFinite(Qt)?Qt:Fe;const bi=He/Ne*1e3,As=Fe/Ne*1e3;for(let jt=0;jt<pt+1;jt++){const ks=At(rt,{..._e,segmentNumber:Wt.toString(10),segmentTime:(Fe+jt*He).toString(10)}),Bi=(As??0)+jt*bi,ws=Bi+bi;Wt++,Rt.push({time:{from:Bi,to:ws},url:ks})}Fe+=(pt+1)*He,Tt+=(pt+1)*bi}Si=Fe/Ne*1e3,gi=At(rt,{..._e,segmentNumber:Wt.toString(10),segmentTime:Fe.toString(10)})}else if(A(u)){const Fe=parseInt(Oe.getAttribute("duration")??"",10)/Ne*1e3,vt=Math.ceil(u/Fe);let He=0;for(let pt=1;pt<vt;pt++){const Qt=At(rt,{..._e,segmentNumber:pt.toString(10),segmentTime:He.toString(10)});Rt.push({time:{from:He,to:He+Fe},url:Qt}),He+=Fe}Si=He,gi=At(rt,{..._e,segmentNumber:vt.toString(10),segmentTime:He.toString(10)})}const $s={time:{from:Si,to:1/0},url:gi};we={type:Ie.TEMPLATE,baseUrl:ve,segmentTemplateUrl:rt,initUrl:mi,totalSegmentsDurationMs:Tt,segments:Rt,nextSegmentBeyondManifest:$s,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!K)continue;const Je={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[ie];Je&&s[Je].push({id:zt,kind:Je,segmentReference:we,profiles:Le,duration:u,bitrate:ee,mime:K,codecs:q,width:xe,height:I,fps:ke,quality:me})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:G,representations:s}},hr=({id:a,width:e,height:t,bitrate:i,fps:s,quality:r})=>{const n=(r?Gt(r):void 0)??St({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},ur=({id:a,bitrate:e})=>({id:a,bitrate:e}),lr=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},pr=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),zi=a=>"size"in a,Et=a=>a.type===Ie.TEMPLATE,Pi=a=>!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20);class qi{onLastSegment$=new f(!1);fullyBuffered$=new f(!1);playingRepresentation$=new f(void 0);playingRepresentationInit$=new f(void 0);error$=new L;gaps=[];subscription=new te;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:r,tuning:n,getCurrentPosition:o,isActiveLowLatency:c,compatibilityMode:d=!1,manifest:h}){switch(this.fetcher=r,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 Dt.MP4:this.containerParser=tr;break;case Dt.WEBM:this.containerParser=dr;break;default:O(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=Ee(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);w(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Pa(this.sourceBuffer),this.subscription.add(C(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(C(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.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,Hi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),r=this.parsedInitData.get(t.id);w(i,"No init buffer for starting representation"),w(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(r))}.bind(this));switchTo=Ee(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);w(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(j(s)||j(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),w(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const r=this.getCurrentPosition();A(r)&&this.maintain(r)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(j(e)||j(this.downloadingRepresentationId)||j(this.playingRepresentationId)||j(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(w(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=dt(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(r=u)}if(isFinite(this.bufferLimit)&&Hi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=dt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,r),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===U.FED&&!o.length&&dt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===U.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const r of e)Math.trunc(r.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from+s}),i=r.time.to;A(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 r=0,n=t.length-1;do s.unshift(t[n]),r+=t[n].time.to-t[n].time.from,n--;while(r<i&&n>=0);return this.liveInitialAdditionalOffset=r-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=Ee(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||!Et(d.segmentReference))return;const h=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);w(i);const s=this.segments.get(t);w(s,"No segments for starting representation");const r=this.initData.get(t);if(w(r,"No init buffer for starting representation"),!(r instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!Et(t.segmentReference))return;const i=t.segmentReference.segments.map(o=>({...o,status:U.NONE,size:void 0})),s=this.segments.get(t.id)??[],r=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.floor(r)>=Math.floor(o.time.from)&&Math.floor(r)<=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(!Et(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),r=At(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:U.NONE,time:{from:e.segment.time.to,to:1/0},url:r})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(r=>r.time.from<=e&&r.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:u,time:{from:p,to:S}},b)=>{const $=p<=i&&S>=i,T=p>i||$||b===0&&i===0,_=Math.min(this.forwardBufferTarget,this.bufferLimit),G=this.preloadOnly&&p<=i+_||S<=i+_;return(u===U.NONE||u===U.PARTIALLY_EJECTED&&T&&G&&this.sourceBuffer&&!ki(this.sourceBuffer.buffered,i))&&T&&G});if(s===-1)return[];if(t!==Ie.BYTE_RANGE)return e.slice(s,s+1);const r=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<r.length&&(n<=d||o<=h);u++){const p=r[u];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status===U.NONE||p.status===U.PARTIALLY_EJECTED)c.push(p);else break}return c}async loadSegments(e,t,i="auto"){t.segmentReference.type===Ie.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=U.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:r,url:n,signal:o,onProgress:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ee(o,async function*(){const d=yi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const d=await this.fetcher.fetch(n,{range:r,signal:o,onProgress:c,priority:i,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const u=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(h,u)}c&&s.feedingBytes?s.segment.status=U.DOWNLOADED:this.sourceBufferTaskQueue.append(h,o).then(u=>{this.onSegmentFullyAppended(s,t.id)}),this.failedDownloads=0}catch(d){if(Pi(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const c of e)c.status=U.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:r,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ee(n,async function*(){const c=yi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(r,{range:s,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(c){if(Pi(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}}prepareByteRangeFetchSegmentParams(e,t){if(Et(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:r}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:s,signal:r,onProgress:(c,d)=>{if(!r.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:d,signal:r,onSegmentAppendFailed:n,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Et(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl).toString(),{signal:s}=this.downloadAbortController,r=()=>{this.abort()},o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:r,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:i,signal:s,onProgress: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&&A(i)&&(t=dt(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:r}){if(!this.activeSegments.size)return;const n=this.representations.get(t);if(n)for(const o of this.activeSegments){const{segment:c}=o;if(o.representationId===t){if(r.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=U.PARTIALLY_FED,o.feedingBytes+=h.byteLength,this.sourceBufferTaskQueue.append(h).then(u=>{o.fedBytes+=h.byteLength,c.status===U.DOWNLOADED&&this.onSegmentFullyAppended(o,n.id)}))}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:r,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,p=c===Ie.BYTE_RANGE,S=p?u.byte.to-u.byte.from+1:d;if(h.representationId!==t||!(!p||u.byte.from>=i&&u.byte.to<i+e.byteLength))continue;if(r.aborted){n();continue}const $=p?u.byte.from-i:0,T=p?u.byte.to-i:e.byteLength,_=$<s,G=T<=s;if(u.status===U.DOWNLOADING&&_&&G){u.status=U.DOWNLOADED,this.activeSegments.delete(h);const m=new DataView(e.buffer,e.byteOffset+$,S);this.sourceBufferTaskQueue.append(m,r).then(E=>E&&!r.aborted?this.onSegmentFullyAppended(h,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&_&&(h.loadedBytes=Math.min(S,s-$),h.loadedBytes>h.feedingBytes)){const m=new DataView(e.buffer,e.byteOffset+$+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===S?m:this.containerParser.parseFeedableSegmentChunk(m);E?.byteLength&&(u.status=U.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,r).then(k=>{if(r.aborted)n();else if(k)h.fedBytes+=E.byteLength,h.fedBytes===S&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<S)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=U.FED,zi(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===U.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=U.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===U.PARTIALLY_FED||e.status===U.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=U.NONE),e.status=U.PARTIALLY_EJECTED):e.status=U.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=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?Ee(this.destroyAbortController.signal,async function*(){const o=yi(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 p=h;this.isLive&&Et(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),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:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||j(e)||this.sourceBuffer.updating)return!1;let s=0,r=1/0,n=-1/0,o=!1;const c=d=>{r=Math.min(r,d.time.from),n=Math.max(n,d.time.to);const h=zi(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===U.FED&&c(h)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===U.FED&&c(h)}}if(o=isFinite(r)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const p of this.segments.values())for(const S of p)if(S.status===U.NONE&&Math.round(S.time.from)<=Math.round(h)&&Math.round(S.time.to)>=Math.round(u)){r=h,n=u;break}}if(o=isFinite(r)&&isFinite(n),!o&&i){s=0,r=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===U.FED&&c(u)}return o=isFinite(r)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(r,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){const n=this.sourceBuffer.buffered.start(r)*1e3,o=this.sourceBuffer.buffered.end(r)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(r=>s&&r.from===s.from&&r.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(j(this.sourceBuffer)||j(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),r=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:r})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:r}=s;if(r!==U.FED&&r!==U.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=U.PARTIALLY_EJECTED:s.status=U.NONE)}}}var kt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(kt||(kt={}));class fr{throughputEstimator;requestQuic;lastConnectionType$=new f(void 0);lastConnectionReused$=new f(void 0);lastRequestFirstBytes$=new f(void 0);abortAllController=new AbortController;subscription=new te;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=us(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=Ee(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Pt(t));const i=yield fetch(t,{signal:this.abortAllController.signal}).catch(It);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=Ee(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?kt.HEADER:kt.PARAM,range:i,onProgress:s,priority:r="auto",signal:n,measureThroughput:o=!0,isLowLatency:c=!1}={}){let d=e;const h=new Headers;if(i)switch(t){case kt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case kt.PARAM:{const B=new URL(d,location.href);B.searchParams.append("bytes",`${i.from}-${i.to}`),d=B.toString();break}default:O(t)}this.requestQuic&&(d=Pt(d));let u=this.abortAllController.signal,p;if(n){const B=new AbortController;if(p=M(C(this.abortAllController.signal,"abort"),C(n,"abort")).subscribe(()=>{try{B.abort()}catch(N){It(N)}}),this.abortAllController.signal.aborted||n.aborted)try{B.abort()}catch(N){It(N)}u=B.signal}const S=re(),b=yield fetch(d,{priority:r,headers:h,signal:u}).catch(It),$=re();if(!b)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt($-S),!b.ok||!b.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!s&&!o)return p?.unsubscribe(),b.arrayBuffer();const[T,_]=b.body.tee(),G=T.getReader();o&&this.throughputEstimator?.trackStream(_,c);let m=0,E=new Uint8Array(0),k=!1;const F=B=>{p?.unsubscribe(),k=!0,It(B)},Q=Ee(u,async function*({done:B,value:N}){if(m===0&&this.lastRequestFirstBytes$.next(re()-S),u.aborted){p?.unsubscribe();return}if(!B&&N){const P=new Uint8Array(E.length+N.length);P.set(E),P.set(N,E.length),E=P,m+=N.byteLength,s?.(new DataView(E.buffer),m),yield G?.read().then(Q,F)}}.bind(this));return yield G?.read().then(Q,F),p?.unsubscribe(),k?null:E.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Ie.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Ie.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:O(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=Ee(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Ie.BYTE_RANGE)return null;const{from:s,to:r}=e.initRange;let n=s,o=r,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=r+1===d,c&&(n=Math.min(d,s),o=Math.max(h,r))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const p=new DataView(u,s-n,r-n+1);if(!t.validateData(p))throw new Error("Invalid media file");const S=t.parseInit(p),b=e.indexRange??t.getIndexRange(S);if(!b)throw new ReferenceError("No way to load representation index");let $;if(c)$=new DataView(u,b.from-n,b.to-b.from+1);else{const _=yield this.fetch(e.url,{range:b,priority:i,measureThroughput:!1});if(!_)return null;$=new DataView(_)}const T=t.parseSegments($,S,b);return{init:S,dataView:new DataView(u),segments:T}}.bind(this));fetchTemplateRepresentation=Ee(this.abortAllController.signal,async function*(e,t){if(e.type!==Ie.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:U.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const It=a=>{if(Pi(a))throw a},Di=1e3,di=(a,e,t)=>t*e+(1-t)*a,Ss=(a,e)=>a.reduce((t,i)=>t+i,0)/e,mr=(a,e,t,i)=>{let s=0,r=t;const n=Ss(a,e),o=e<i?e:i;for(let c=0;c<o;c++)a[r]>n?s++:s--,r=(a.length+r-1)%a.length;return Math.abs(s)===o};class Ii{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 f(e.initial),this.debounced$=new f(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ze(`raw_${t}`),this.smoothedSeries$=new ze(`smoothed_${t}`),this.reportedSeries$=new ze(`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),r=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>r||this.smoothed<n)&&(j(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 gr extends Ii{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=di(this.slow,e,this.params.emaAlphaSlow),this.fast=di(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Sr extends Ii{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Ss(this.pastMeasures,this.takenMeasures);this.emaSmoothed=di(this.emaSmoothed,e,this.params.emaAlpha);const i=mr(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class br extends Ii{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?di(this.smoothed,e,this.params.emaAlpha):e}}class xi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new gr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Sr({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 br({initial:e,label:"liveEdgeDelay",...t})}}const yr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Wi=["timeupdate","progress","play","seeked","stalled","waiting"];var Ce;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Ce||(Ce={}));let Tr=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new te;representationSubscription=new te;fetcher;state$=new oe(Ce.NONE);currentVideoRepresentation$=new f(void 0);currentVideoRepresentationInit$=new f(void 0);error$=new L;lastConnectionType$=new f(void 0);lastConnectionReused$=new f(void 0);lastRequestFirstBytes$=new f(void 0);isLive$=new f(!1);liveDuration$=new f(0);liveAvailabilityStartTime$=new f(void 0);bufferLength$=new f(0);liveLoadBufferLength$=new f(0);livePositionFromPlayer$=new f(0);liveEstimatedDelay;isActiveLowLatency=!1;isUpdatingLive=!1;forceEnded$=new L;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new fr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=xi.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=Ee(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Qe(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ce.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Ce.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=Ee(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=cr(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:r,codecs:n})=>!!(this.element?.canPlayType?.(r)&&window.MediaSource?.isTypeSupported?.(`${r}; codecs="${n}"`)||s===Se.TEXT);return 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,r])=>[s,r.filter(i)]))}}.bind(this));async seekLive(e){w(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.manifestUrlString=Qe(this.manifestUrlString,e,fe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=Ee(this.destroyController.signal,async function*(e,t){w(this.manifest),w(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ce.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new qi(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],A(t)&&(this.audioBufferManager=new qi(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ii(Di).subscribe(n=>{if(this.element?.paused){const o=Mi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Qe(this.manifestUrlString,o+Di,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(M(...Wi.map(n=>C(this.element,n))).pipe(v(n=>this.element?dt(this.element.buffered,this.element.currentTime*1e3):0),he(),J(n=>!!n)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(J(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 p=1+Math.sign(u)*h;Math.abs(u)<d?p=1:Math.abs(u)>d*2&&(p=1+Math.sign(u)*h*2),yr(this.element,p)})),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($e({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:o,bufferLength:c})=>{if(w(this.element),this.isUpdatingLive)return;const d=this.element.playbackRate,h=Mi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),u=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,p=Math.min(u,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*d),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*d,b=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*d,$=this.isActiveLowLatency?c:o;let T=Ge.None;if(this.isActiveLowLatency?T=Ge.ActiveLowLatency:$<p+b&&$>=p?T=Ge.LiveWithTargetOffset:h!==0&&$<p&&(T=Ge.LiveForwardBuffering),isFinite(o)&&(n=o>n?o:n),T===Ge.LiveForwardBuffering||T===Ge.LiveWithTargetOffset){const _=n-(p+S),G=Math.trunc(h+_/d);let m;o?G>0?m=G:m=0:m=h,this.manifestUrlString=Qe(this.manifestUrlString,m,fe.DASH_CMAF_OFFSET_P)}T!==Ge.None&&T!==Ge.ActiveLowLatency&&(n=0,this.updateLive())}))}const s=M(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(v(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),r=M(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(v(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(M(this.forceEnded$,$e({allBuffersFull:s,someBufferEnded:r}).pipe(J(({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:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(M(...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))),A(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&A(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Ce.REPRESENTATIOS_READY)}.bind(this));initBuffer(){w(this.element),this.state$.setState(Ce.RUNNING),this.subscription.add(M(...Wi.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ki(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e]?.switchTo(t)}seek(e,t){w(this.element),w(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ki(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ce.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=ii(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const r of s.gaps)s.playingRepresentation$.getValue()===r.representation&&r.from<=t&&r.to>t&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?i.push(1/0):i.push(r.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class vr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Er{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,r=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:s,y:r,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var $r=`#define GLSLIFY 1
30
- attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,Ar=`#ifdef GL_ES
25
+ [best track] ${W.quality}
26
+ [selected track] ${G.quality}
27
+ `});const Q=G&&d&&d.history[G.id]&&ue()-d.history[G.id]<=i.trackCooldown&&(!d.last||G.id!==d.last.id);if(G?.id&&d&&!Q&&d.recordSelection(G),Q&&d?.last){const A=d.last;return d?.recordSwitch(A),u({message:`
28
+ [last selected] ${A.quality}
29
+ `}),A}return d?.recordSwitch(G),G};var $e=a=>new URL(a).hostname;const ea=300,ei=(a,e=ea)=>new ni(t=>{const{width:i,height:s}=a.getBoundingClientRect();if(t.next({width:i,height:s}),!window.ResizeObserver)return;const r=new ResizeObserver(Ds(n=>{const o=n[0];if(!o)return;let c,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,c=o.contentBoxSize[0].inlineSize):o.contentRect&&(c=o.contentRect.width,d=o.contentRect.height),w(c)&&w(d)&&t.next({width:c,height:d})},e));return r.observe(a),()=>r.disconnect()});class di{onDroopedVideoFramesLimit$=new x;subscription=new te;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new x;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(L(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Zt(this.droppedFramesChecker.checkTime).pipe(K(()=>this.playing),K(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Ie(this.droppedFramesChecker.checkTime)),i=B(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Nt(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,s=t-this.prevDroppedVideoFrames,r=1-(i-s)/i;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&It(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)};onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){const t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[s])=>Jt(i,s)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const _t={};var Y;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));const pe=(a,e)=>new ni(t=>{const i=s=>t.next(s);return a.on(e,i),()=>a.off(e,i)});class Li{subscription=new te;videoState=new ne(Y.DOWNLOADING_LIB);video;player;params;textTracksManager=new Ge;droppedFramesManager=new di;videoTracks$=new m([]);frameRatesByFrameHeight={};isLive$=new m(void 0);maxSeekBackTime$=new m(1/0);availableFrom$=new m(void 0);elementSize$=new m(void 0);liveOffset=new oi;constructor(e){this.video=Ke(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next($e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:C.NETWORK,message:`Dash.js failed to load: ${s?.toString?.()}`,thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(_t.MediaPlayer=s.MediaPlayer,_t.Debug=s.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(_t.MediaPlayer,"dashjs not loaded"),P(_t.Debug,"dashjs not loaded"),this.player=_t.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?Ai(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Us(this.player),Os(this.player),this.params.tuning.requestQuick&&Vs(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:C.WTF,message:"DashIFProvider internal logic error",thrown:g})},s=(g,$)=>this.subscription.add(g.subscribe($,i));s(ei(this.video),this.elementSize$),s(pe(this.player,"error").pipe(y(g=>{const $=typeof g.error=="object"?g.error.code:g.error,k=typeof g.error=="object"?g.error.message:void 0;return{id:`DashJS#${$}`,message:k}})),e.error$),s(pe(this.player,"playbackError").pipe(y(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const r=pe(this.player,"qualityChangeRendered").pipe(K(({mediaType:g})=>g==="video"),y(({newQuality:g})=>this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g)?.track));r.pipe(K(w)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(K(({to:g})=>g===Y.STREAM_INITIALIZED),le()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{const g=this.player.getQualityFor("video");return this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g)?.track?.id},g=>{if(J(g))return;const $=this.videoTracks$.getValue().find(({track:k})=>k.id===g)?.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:r.pipe(y(g=>g?.id)),onError:i}))},i)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,g=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:g}}}}),{onError:i})),s(pe(this.player,"bufferStateChanged").pipe(K(({mediaType:g})=>g==="video"),y(({state:g})=>g==="bufferStalled")),e.isBuffering$),s(pe(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:$}})=>{const k=this.player.getDashMetrics(),O=k.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),W=k.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type")??Ot.HTTP1,G={1:!0,0:!1}[O]??void 0;this.params.output.httpConnectionType$.next(W),this.params.output.httpConnectionReused$.next(G),e.hostname$.next($e($))}),s(pe(this.player,"streamInitialized"),({streamInfo:{duration:g,manifestInfo:{isDynamic:$,availableFrom:k}}})=>{this.isLive$.next($),this.availableFrom$.next(k.getTime()),$||e.duration$.next(g);const O=[],W=this.player.getQualityFor("video");let G;for(const Q of this.player.getBitrateInfoListFor("video")){const A=Q.qualityIndex.toString(10),F=pt(Q),q=Q.bitrate/1e3,ie={width:Q.width,height:Q.height},be=this.frameRatesByFrameHeight[Q.height];if(F){const _e={id:A,quality:F,bitrate:q,size:ie,fps:be};O.push({track:_e,bitrateInfo:Q}),Q.qualityIndex===W&&(G=_e)}}this.videoTracks$.next(O),e.availableVideoTracks$.next(O.map(({track:Q})=>Q)),G&&e.currentVideoTrack$.next(G),this.videoState.setState(Y.STREAM_INITIALIZED),this.videoState.startTransitionTo(Y.READY)}),s(pe(this.player,"fragmentLoadingCompleted"),({request:g})=>{if(!g.requestEndDate||!g.firstByteDate||!g.bytesLoaded)return;const $=g.requestEndDate.getTime()-g.firstByteDate.getTime(),k=g.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(k,$)}),s(B(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const g=this.params.dependencies.throughputEstimator.throughput$.getValue(),$=$t(this.videoTracks$.getValue().map(({track:W})=>W),{container:this.elementSize$.getValue(),throughput:g,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),k=t.autoVideoTrackLimits.getTransition();k&&e.autoVideoTrackLimits$.next(k.to);const O=this.videoTracks$.getValue().find(({track:W})=>W===$);O?.bitrateInfo&&this.player.setQualityFor("video",O?.bitrateInfo.qualityIndex,!1)}),s(De({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(K(w))}).pipe(K(({isLive:g})=>g),y(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const n=pe(this.player,"playbackTimeUpdated").pipe(y(({time:g})=>g??0));s(De({availableFrom:this.availableFrom$.pipe(K(w)),currentTime:n}),({availableFrom:g,currentTime:$})=>this.params.output.liveTime$.next(g+$*1e3)),s(n.pipe(K(()=>this.isLive$.getValue()===!1)),e.position$),s(pe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(pe(this.player,"playbackEnded"),e.endedEvent$),s(pe(this.player,"playbackProgress").pipe(y(()=>ss(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(pe(this.player,"playbackPlaying"),()=>{this.videoState.setState(Y.PLAYING),D(t.playbackState,l.PLAYING)}),s(pe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Y.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(pe(this.player,"playbackPaused"),()=>{this.videoState.setState(Y.PAUSED),D(t.playbackState,l.PAUSED)}),s(pe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY)}),s(this.isLive$,e.isLive$),s(ei(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ee(["init"])).pipe(Ie(0));s(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=Fs(this.player);s(h,this.params.output.httpConnectionType$),s(u,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(d.pipe(le()),e.firstBytesEvent$),s(pe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(De({isLive:this.isLive$,isShort:e.duration$.pipe(y(g=>g<60))}),({isLive:g,isShort:$})=>{const k=!g&&$;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:k}}})}),s(n.pipe(K(g=>g>this.params.tuning.insufficientBufferRuleMargin),le()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(pe(this.player,"manifestLoaded").pipe(le()).subscribe(()=>{this.subscription.add(pe(this.player,"playbackPlaying").pipe(le(),Tt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),s(pe(this.player,"manifestLoaded"),g=>{if(g.data?.Period?.AdaptationSet){const $=[];for(const k of g.data?.Period?.AdaptationSet)if(k.contentType==="text"){const O=k.Representation?.id,W=new URL(k.Representation?.BaseURL,g.data?.baseUri).toString(),G="internal",Q=k.lang;$.push({id:O,url:W,type:G,language:Q})}t.internalTextTracks.startTransitionTo($)}}),this.subscription.add(ft(this.video,t.isLooped,i));const{volumeState$:p,looped$:f,playbackRateState$:b,inPiP$:E,inFullscreen$:v,pause$:R,playing$:N}=et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:N,pause$:R,tracks$:this.videoTracks$.pipe(y(g=>g.map(({track:$})=>$)))}),this.subscription.add(Xe(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(nt(this.video,t.playbackRate,b,i)),this.subscription.add(E.subscribe(e.inPiP$)),this.subscription.add(v.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Y.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Y.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=Ye(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,fe.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(Y.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===Y.DOWNLOADING_LIB||e===Y.STREAM_INITIALIZED))switch(i?.to!==l.PAUSED&&s.state===H.Requested&&e!==Y.STOPPED&&t!==l.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),t){case l.STOPPED:{switch(e){case Y.STOPPED:break;case Y.PLAYING:case Y.PAUSED:case Y.READY:this.stop();break;default:M(e)}break}case l.READY:{switch(e){case Y.STOPPED:this.prepare();break;case Y.PLAYING:case Y.PAUSED:case Y.READY:break;default:M(e)}break}case l.PLAYING:{switch(e){case Y.PLAYING:break;case Y.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Y.READY:this.play();break;case Y.STOPPED:this.prepare();break;default:M(e)}break}case l.PAUSED:{switch(e){case Y.PLAYING:this.pause(),this.liveOffset.pause();break;case Y.PAUSED:break;case Y.READY:this.videoState.setState(Y.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED);break;case Y.STOPPED:this.prepare();break;default:M(e)}break}default:M(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{this.player?.destroy()}catch{}Ze(this.video),this.params.output.element$.next(void 0)}}var Vt=a=>{switch(a){case"mobile":return Re.Q_144P;case"lowest":return Re.Q_240P;case"low":return Re.Q_360P;case"sd":case"medium":return Re.Q_480P;case"hd":case"high":return Re.Q_720P;case"fullhd":case"full":return Re.Q_1080P;case"quadhd":case"quad":return Re.Q_1440P;case"ultrahd":case"ultra":return Re.Q_2160P}};const Ii=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var ot=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!Ii(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return Ii(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function ye(){return ue()}function as(a){return ye()-a}function Bi(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,c=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return c&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ta(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Xt(a,e,t,i){const s=window.XMLHttpRequest;let r,n,o,c=!1,d=0,h,u,p=!1,f="arraybuffer",b=7e3,E=2e3,v=()=>{if(c)return;P(h);const q=as(h);let ie;if(q<E){ie=E-q,setTimeout(v,ie);return}E*=2,E>b&&(E=b),n&&n.abort(),n=new s,O()};const R=q=>(r=q,F),N=q=>(u=q,F),g=()=>(f="json",F),$=()=>{if(!c){if(--d>=0){v(),i&&i();return}c=!0,u&&u(),t&&t()}},k=q=>(p=q,F),O=()=>{h=ye(),n=new s,n.open("get",a);let q=0,ie,be=0;const _e=()=>(P(h),Math.max(h,Math.max(ie||0,be||0)));if(r&&n.addEventListener("progress",I=>{const ee=ye();r.updateChunk&&I.loaded>q&&(r.updateChunk(_e(),I.loaded-q),q=I.loaded,ie=ee)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(c)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&r){const ee=n.response.byteLength-q;ee&&r.updateChunk&&r.updateChunk(_e(),ee)}u&&u(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),p){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(be=ye(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),F},F={withBitrateReporting:R,withParallel:k,withJSONResponse:g,withRetryCount:q=>(d=q,F),withRetryInterval:(q,ie)=>(w(q)&&(E=q),w(ie)&&(b=ie),F),withTimeout:q=>(o=q,F),withFinally:N,send:O,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return F}const ia=100,sa=2e3,aa=500;let ra=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-aa;if(t-e>sa){let i=0,s=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)i+=r.end-r.start,s+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;i+=n;const c=r.bytes*n/o;s+=c,r.start=t,r.bytes-=c}}}if(s>0&&i>0){const r=s*8/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>ia&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class na{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=ye(),s=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},r=c=>{e._complete=1,e._responseData=c,e._downloadTime=ye()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Xt(t,r,()=>s("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ye()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=ye();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,s){const r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=r._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),r._finallyCB&&r._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(r,e)}},r._cb=t,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=n=>(r._finallyCB=n,r),r}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Wt=1e4,Qt=3,oa=300,da=2e3,ca=6e4,ua=10,ha=1,la=500;class pa{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new ra(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bi(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Bi(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,r;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)r=this.manifest[o],!(this.maxAutoQuality&&r.video.height>this.maxAutoQuality)&&(r.bitrate<e&&n>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||w(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{ta(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new na(Qt,Wt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let r=!1,n=null,o=null,c=null,d=null,h=!1;const u=()=>{const $=r&&(!h||h===this.rep);return $||t("Not running!"),$},p=($,k,O)=>{c&&c.abort(),c=Xt(this.urlResolver.resolve($,!1),k,O,()=>this._retryCallback()).withTimeout(Wt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qt).withFinally(()=>{c=null}).send()},f=($,k,O)=>{P(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),k,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=$=>{const k=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${k}=>${$}`),i.playbackRate=$)},E=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const O=ye()-1e4;let W=0;for(let Q=0;Q<this.bufferStates.length;Q++){const A=this.bufferStates[Q];$=Math.min($,A.buf),A.ts<O&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${$} drop=${W} jitter=${this.sourceJitter}`);let G=$-ha;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?b(1.15):G>1?b(1.1):G>.3?b(1.05):b(1)}},R=$=>{let k;const O=()=>k&&k.start?k.start.length:0,W=I=>k.start[I]/1e3,G=I=>k.dur[I]/1e3,Q=I=>k.fragIndex+I,A=(I,ee)=>({chunkIdx:Q(I),startTS:W(I),dur:G(I),discontinuity:ee}),F=()=>{let I=0;if(k&&k.dur){let ee=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,he=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=ee;this.sourceJitter>1&&(me+=this.sourceJitter-1);let ke=k.dur.length-1;for(;ke>=0&&(me-=k.dur[ke],!(me<=0));--ke);I=Math.min(ke,k.dur.length-1-he),I=Math.max(I,0)}return A(I,!0)},q=I=>{const ee=O();if(!(ee<=0)){if(w(I)){for(let he=0;he<ee;he++)if(W(he)>I)return A(he)}return F()}},ie=I=>{const ee=O(),he=I?I.chunkIdx+1:0,me=he-k.fragIndex;if(!(ee<=0)){if(!I||me<0||me-ee>ua)return t(`Resync: offset=${me} bChunks=${ee} chunk=`+JSON.stringify(I)),F();if(!(me>=ee))return A(he-k.fragIndex,!1)}},be=(I,ee,he)=>{d&&d.abort(),d=Xt(this.urlResolver.resolve(I,!0,this.lowLatency),ee,he,()=>this._retryCallback()).withTimeout(Wt).withRetryCount(Qt).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,ee)=>{be($,he=>{if(!u())return;k=he;const me=!!k.lowLatency;me!==this.lowLatency&&E(me);let ke=0;for(let tt=0;tt<k.dur.length;++tt)ke+=k.dur[tt];ke>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ke/k.dur.length)),s({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,I(q(ee))},()=>this._handleNetworkError())},nextChunk:ie}},N=()=>{r=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:$=>{const{videoElement:k,logger:O}=this.params;let W=R(e.jidxUrl),G,Q,A,F,q=0,ie,be,_e;const I=()=>{ie&&(clearTimeout(ie),ie=void 0);const Z=Math.max(la,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ve=q+Z,xe=ye(),Ae=Math.min(1e4,ve-xe);q=xe;const dt=()=>{d||u()&&W.seek(()=>{u()&&(q=ye(),ee(),I())})};Ae>0?ie=window.setTimeout(()=>{this.paused?I():dt()},Ae):dt()},ee=()=>{let Z;for(;Z=W.nextChunk(F);)F=Z,ui(Z);const ve=W.nextChunk(A);if(ve){if(A&&ve.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?I():(N(),this._initPlayerWith(e));return}tt(ve)}else I()},he=(Z,ve)=>{if(!u()||!this.sourceBuffer)return;let xe,Ae,dt;const Be=ze=>{window.setTimeout(()=>{u()&&he(Z,ve)},ze)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Be(100);else{const ze=ye(),Oe=k.currentTime;!this.paused&&k.buffered.length>1&&be===Oe&&ze-_e>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),be!==Oe&&(be=Oe,_e=ze);const We=this._getBufferSizeSec();if(We>30)O(`Buffered ${We} seconds; delaying appendBuffer`),Be(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:ze,buf:We}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ve&&ve()}catch(mt){if(mt.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),dt=this.sourceBuffer.buffered.length,dt!==0&&(xe=this.sourceBuffer.buffered.start(0),Ae=Oe,Ae-xe>4&&this.sourceBuffer.remove(xe,Ae-3)),Be(1e3);else throw mt}}},me=()=>{Q&&G&&(O([`Appending chunk, sz=${Q.byteLength}:`,JSON.stringify(A)]),he(Q,function(){Q=null,ee()}))},ke=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),tt=Z=>{u()&&f(ke(Z),(ve,xe)=>{if(u()){if(xe/=1e3,Q=ve,A=Z,n=Z.startTS,xe){const Ae=Math.min(10,Z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}me()}},()=>this._handleNetworkError())},ui=Z=>{u()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ke(Z),!1)))},Ht=Z=>{u()&&(e.cachedHeader=Z,he(Z,()=>{G=!0,me()}))};r=!0,W.seek(Z=>{if(u()){if(q=ye(),!Z){I();return}F=Z,!J($)||Z.startTS>$?tt(Z):(A=Z,ee())}},$),e.cachedHeader?Ht(e.cachedHeader):p(e.headerUrl,Ht,()=>this._handleNetworkError())},stop:N,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),w(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return w(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=u=>{if(!this.autoQuality)return;let p,f,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(f=this._getBufferSizeSec(),b=u/this.bitrate,f>10&&b>.8||f>15&&b>.5||f>20&&b>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}p=this._selectQuality(u),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${u}`)},r=(()=>({updateChunk:(p,f)=>{const b=ye();if(this.chunkRateEstimator.addInterval(p,b,f)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:b-p,speed:v}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=r.get();if(u&&o&&this.autoQuality){if(c&&u>o&&as(n)<3e4)return;i(u)}c=this.autoQuality};return{updateChunk:(u,p)=>{const f=r.updateChunk(u,p);return f&&d(),f},notifySwitch:u=>{const p=ye();u<o&&(n=p),o=u}}}_fetchManifest(e,t,i){this.manifestRequest=Xt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Wt).withRetryCount(Qt).withRetryInterval(oa,da).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ot(t).then(i=>{i||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,r=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&s.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=d,o.push(c))}),o.sort(function(c,d){return c.video&&d.video?d.video.height-c.video.height:d.bitrate-c.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=r(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ca))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var U;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(U||(U={}));const fa=[U.PAUSED,U.PLAYING,U.READY],ma=[U.PAUSED,U.PLAYING,U.READY];class ga{subscription=new te;video;videoState=new ne(U.STOPPED);dash;representations$=new m([]);textTracksManager=new Ge;droppedFramesManager=new di;maxSeekBackTime$=new m(1/0);zeroTime$=new m(void 0);liveOffset=new oi;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:s})};B(this.videoState.stateChangeStarted$.pipe(y(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(y(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(s)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next($e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(y(s=>s.map(({track:r})=>r)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(U.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ce(),y(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(De({zeroTime:this.zeroTime$.pipe(K(w)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:r})=>this.params.output.liveTime$.next(s+r*1e3),t)).add(ft(this.video,this.params.desiredState.isLooped,t)).add(Xe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const r=s&&$s(s);this.dash.setMaxAutoQuality(r),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case U.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case U.MANIFEST_READY:case U.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case U.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case U.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return M(s.to)}},t)).add(B(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ee(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}createLiveDashPlayer(){const e=new pa({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&w(t)?t:$t(e.map(({track:c})=>c),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id,r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.videoTrack.getState(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((r&&s||s!==n)&&this.setVideoTrack(s),o&&this.setAutoQuality(i),r||o||s!==n){const c=e.find(({track:d})=>d.id===s)?.representation;P(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e)?.representation;P(t,`No such representation ${e}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===U.PAUSED,r=-e,n=r<=this.maxSeekBackTime$.getValue()?r:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ye(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:C.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const r=s.name??s.index.toString(10),n=Vt(s.name)??pt(s.video),o=s.bitrate/1e3,c={...s.video};if(!n)continue;const d={id:r,quality:n,bitrate:o,size:c};i.push({track:d,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===U.MANIFEST_READY&&this.videoState.setState(U.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),w(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(U.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ma.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==l.PAUSED&&r.state===H.Requested&&fa.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_READY),this.dash.attachSource(Ye(this.params.source.url));return;case U.MANIFEST_READY:this.videoState.startTransitionTo(U.READY),this.prepare();break;case U.READY:if(i===l.PAUSED)this.videoState.setState(U.PAUSED);else if(i===l.PLAYING){this.videoState.startTransitionTo(U.PLAYING);const c=s?.from;c&&c===l.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)})}return;case U.PLAYING:i===l.PAUSED&&(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case U.PAUSED:i===l.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return M(e)}}}var rs=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?Ot.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},rt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,r=a.end(i)*1e3;s<=e&&e<=r&&(t=r)}return Math.max(t-e,0)};const Sa=a=>{const e=document.createElement("a");return e.href=a,e.origin},ba=a=>{const e=document.createElement("a");return e.href=a,e.host};class ns{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],i,s,r,n){this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(this._xhr){if(this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(i=>i.split(":").map(s=>s.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(ba(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",t,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class ti{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let r=0;for(let n=0,o=s.length;n<o;n++)r+=s.end(n)-s.start(n);r&&(this._maxBufferDuration=Math.round(r))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,s,r,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,p=0;const f=E=>{s(ti._str2ua(E.substr(c))),c=E.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=yt(b)),this._lastXhr=new ns(b,e.failoverHosts,E=>{this._lastXhr=void 0,f(E);const v=Date.now()-d;this._params.onBandwidthChange({size:E.length,duration:v,speed:8*E.length/(v/1e3)}),this._onDashCallback("loading",{size:E.length,done:!0}),r?.()},E=>{if(E.length-c>o&&f(E),u===0){u=Date.now();return}p=E.length-h;const v=Date.now()-u;p>=100*1024&&v>=1e3&&(this._params.onBandwidthChange({size:p,duration:v,speed:8*p/(v/1e3)}),p=0,h=E.length,u=Date.now()),this._onDashCallback("loading",{size:E.length,done:!1})},n,(E,v,R)=>this._params.onError(E,v,R))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=ti._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Ta{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},s=t.exec(e),r=s?.[1]==="-"?-1:1,n={years:i(s?.[2],r),months:i(s?.[3],r),weeks:i(s?.[4],r),days:i(s?.[5],r),hours:i(s?.[6],r),minutes:i(s?.[7],r),seconds:i(s?.[8],r)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=yt(i)),new ns(i,t,s=>{this.attachManifest(s,t,Sa(i))},void 0,s=>{this._params.onResponseHeaders(s)},(s,r,n)=>this._params.onError(s,r,n))}attachManifest(e,t,i){const r=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,h)=>{const u=d.attributes.getNamedItem(h);return u?u.value:null};this._duration=this._parseDurationFromISO8601(String(n(r,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(r.getElementsByTagName("Representation"),d=>{const h=d.getElementsByTagName("SegmentBase")[0],u=h&&n(h,"indexRange").split("-"),p=h&&h.getElementsByTagName("Initialization")[0],f=p&&n(p,"range").split("-");if(!f||!u){const g=d.parentElement;if(g?.getAttribute("contentType")==="text"){const $=d.getAttribute("id")??void 0,k=(i?i+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,O=g.getAttribute("lang")??void 0;k&&c.push({id:$,url:k,language:O})}return}const b=.1,E=Number(d.attributes.getNamedItem("bandwidth")?.value),v=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let R;const N=d.attributes.getNamedItem("frameRate")?.value??void 0;R=N?Ai(N):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:E,baseURL:v,failoverHosts:t,indexFrom:Number(u[0]),indexTo:Number(u[1]),initFrom:Number(f[0]),initTo:Number(f[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:R,bufferSize:b*E/8,bufferLength:b,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:h,url:u})=>{const p=document.createElement("track");u&&p.setAttribute("src",u),d&&p.setAttribute("id",d),h&&p.setAttribute("srclang",h),this._video.appendChild(p)}),this._representations.sort((d,h)=>h.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:c})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let r=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,r);const n=new DataView(s.buffer);r+=12;const o=n.getUint32(r+4,!1);r+=8;let c=n.getUint32(r,!1),d=n.getUint32(r+4,!1)+(e.indexTo+1);r+=8;const h=n.getUint16(r+2,!1);r+=4,e.refs=[];for(let p=0;p<h;p+=1){const f=d+(n.getUint32(r,!1)&2147483647),b=c+n.getUint32(r+4,!1);r+=12,e.refs.push({fromTime:c/o,toTime:b/o,fromOffset:d,toOffset:f-1}),d=f,c=b}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let s,r;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const h=this._appendVector[String(d.fromTime)];h!==s&&(s=h,this._params.onRepresentationPlay(h));let u;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}u=f.to-this._video.currentTime,u<e.bufferLength&&(this._onDashCallback("buffering"),r!==f.to&&(r=f.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(f);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},u*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},c=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ti({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",c),i.removeEventListener("webkitsourceopen",c)};i.addEventListener("sourceopen",c,!1),i.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const r=this._findRef(t);if(r){if(i){this._isLastRef(r)&&t>=r.toTime&&(t=r.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:r.fromTime}this._appendVector[String(r.fromTime)]=e,this._stream.load(e,r.fromOffset,r.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=r.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const r=.1;if(s.toTime<i.to+r){const n=this._findRef(s.toTime);n&&n.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,n.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||J(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let i;for(let s=0;s<t.length;s++){const r=t[s];if(r.fromTime<=e&&r.toTime>e)return r;r.fromTime>e&&(!i||r.fromTime<i.fromTime)&&(i=r)}if(!i){const s=t[t.length-1];if(e>s.toTime)return s}return i}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const i=t[t.length-1];return e.fromTime===i.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>i&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var z;(function(a){a.STOPPED="stopped",a.MANIFEST_LOADED="manifest-loaded",a.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",a.METADATA_LOADED="metadata-loaded",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const ya=[z.PAUSED,z.PLAYING];class va{videoState=new ne(z.STOPPED);subscription=new te;video;buffer;dash;representations$=new m([]);currentRepresentation$=new m(void 0);params;textTracksManager=new Ge;droppedFramesManager=new di;elementSize$=new m(void 0);dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),B(this.videoState.stateChangeStarted$.pipe(y(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(y(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next($e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ws(this.video),this.dash=new Ta({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:s,category:C.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:C.WTF,message:"DashProvider internal logic error",thrown:o})},s=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},r=et(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(r.seeking$.subscribe(()=>{J(this.params.desiredState.seekState.getState().state!==H.Applying)&&(this.videoState.getState()===z.PLAYING||this.videoState.getState()===z.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(Xe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(y(o=>o.map(({track:c})=>c)))}),n(ei(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)})).add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),D(this.params.desiredState.playbackState,l.PLAYING)},i)).add(r.loadedMetadata$.subscribe(()=>{this.videoState.setState(z.METADATA_LOADED)},i)).add(r.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(y(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:C.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(B(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,L(this.video,"progress")).pipe(y(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),h=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),f=s();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let b;if(!f&&w(h))b=h;else{const E=rt(this.video.buffered,this.video.currentTime*1e3),v=f?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,R=Math.min(E/v,1);b=$t(c.map(({track:g})=>g),{container:p,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:R,playbackRate:this.video.playbackRate,current:c.find(({representation:g})=>g===o)?.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger})?.id;const N=t.autoVideoTrackLimits.getTransition();N&&e.autoVideoTrackLimits$.next(N.to)}return w(b)?c.find(({track:E})=>E.id===b)?.representation:void 0}),ce()).subscribe(this.currentRepresentation$,i)).add(De({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(K(o=>o.to===z.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(K(w))}).pipe(le()).subscribe(()=>this.videoState.setState(z.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(K(w),ce((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?o.height<=c.height:o===c)).subscribe(o=>{const c=rt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!s())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next($e(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=rs(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(le(),Tt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(K(w)).subscribe(this.handleRepresentationPlay,i)).add(B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ee(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return M(e)}}handleManifestReady=({representations:e,textRepresentations:t})=>{const i=[];for(const s of e){const r=s.name??s.id??s.height.toString(10),n=(s.name&&Vt(s.name))??pt(s),o=s.bandwidth/1e3,c={width:s.width,height:s.height},d=s.fps;if(!n)continue;const h={id:r,quality:n,bitrate:o,size:c,fps:d};i.push({track:h,representation:s})}if(this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),t?.length>0){const s=[];for(const r of t){const n=r.id||`${r.language}_${Date.now()}`;s.push({id:n,type:"internal",url:r.url||"",language:r.language,isAuto:r.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(s)}this.videoState.setState(z.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:i})=>i===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return P(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){ot(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(s?.to!==l.PAUSED&&r.state===H.Requested&&ya.includes(e)&&this.seek(r.position,r.forcePrecise),e){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_LOADED),this.prepare();return;case z.MANIFEST_LOADED:this.videoState.startTransitionTo(z.INITIAL_REPRESENTATION_SELECTED);return;case z.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(z.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case z.METADATA_LOADED:this.videoState.startTransitionTo(z.READY),this.dash.updateRefsForCurrentTime();return;case z.READY:i===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(z.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case z.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return M(e)}}}var Se;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Se||(Se={}));var ii;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ii||(ii={}));var Le;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Le||(Le={}));var j;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(j||(j={}));var vt;(function(a){a.MP4="mp4",a.WEBM="webm"})(vt||(vt={}));var si;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(si||(si={}));var oe;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(oe||(oe={}));var yi=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};let os=!1;try{os=$i().browser===es.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Ea{bufferFull$=new x;error$=new x;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const r={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let i;os&&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:C.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:C.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:M(t)}}}var Mi=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class qe{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class ds extends qe{}class $a extends qe{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class ka extends qe{parseChildrenBoxes(){return kt(this.content)}}class Aa extends qe{data;constructor(e){super(e),this.data=this.content}}class Ut extends qe{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class wa extends Ut{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,r=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:r,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class Pa extends qe{parseChildrenBoxes(){return kt(this.content)}}class Da extends qe{parseChildrenBoxes(){return kt(this.content)}}var lt;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(lt||(lt={}));class _a extends Ut{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=lt.MONOSCOPIC;break;case 1:this.stereoMode=lt.TOP_BOTTOM;break;case 2:this.stereoMode=lt.LEFT_RIGHT;break;case 3:this.stereoMode=lt.STEREO_CUSTOM;break;case 4:this.stereoMode=lt.RIGHT_LEFT;break}this.cursor+=1}}class xa extends Ut{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Ra extends Ut{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 Ca extends qe{parseChildrenBoxes(){return kt(this.content)}}class La extends Ut{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 Ia extends qe{parseChildrenBoxes(){return kt(this.content)}}class Ba extends qe{parseChildrenBoxes(){return kt(this.content)}}const Ma={ftyp:$a,moov:ka,mdat:Aa,sidx:wa,trak:Pa,mdia:Ca,tkhd:La,minf:Ia,sv3d:Da,st3d:_a,prhd:xa,proj:Ba,equi:Ra,unknown:ds};class Na{createBox(e,t){const i=Ma[e];return i?new i(t):new ds(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return ci.createBox(i,new DataView(e.buffer,e.byteOffset))}}const ci=new Na;function Lt(a,e){const t=new TextDecoder("ascii");let i=a.byteOffset,s=[];for(;i<a.byteLength;){const r=t.decode(new DataView(a.buffer,i,1));if(r===e[s.length]?s.push(r):s=[],s.length===4&&s.join("")===e){const o=new DataView(a.buffer,i-7,4).getUint32(0);return i-7+o>a.byteLength?null:ci.createBox(e,new DataView(a.buffer,i-7))}i++}return null}function Oa(a,e){const t=[];let i=0;for(;i<a.byteLength;){const s=Lt(new DataView(a.buffer,a.byteOffset+i,a.byteLength-i),e);if(s)t.push(s),i+=s.size+s.source.byteOffset;else break}return t}function kt(a){const e=[];let t=0;for(;t<a.byteLength;){const i=ci.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Fa=new TextDecoder("ascii"),Va=a=>Fa.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Ua=a=>{const e=ci.createFromView(a);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(r=>{if(r.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=r.subsegmentDuration/e.timescale*1e3,o={status:j.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+r.referencedSize-1}};return t+=n,i+=r.referencedSize,o})},Ha=a=>{const e=Oa(a,"mdat");if(e.length){const t=e.reduce((i,s)=>i+s.size,0);return new DataView(a.buffer,a.byteOffset,t)}return null},Ya=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:si.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Lt(a,"sv3d")){e.is3dVideo=!0;const i=Lt(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=Lt(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const r=Lt(a,"equi");r&&(e.projectionData.bounds.top=r.projectionBoundsTop,e.projectionData.bounds.right=r.projectionBoundsRight,e.projectionData.bounds.bottom=r.projectionBoundsBottom,e.projectionData.bounds.left=r.projectionBoundsLeft)}return e},Ga={validateData:Va,parseInit:Ya,getIndexRange:()=>{},parseSegments:Ua,parseFeedableSegmentChunk:Ha};var T;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(T||(T={}));var _;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(_||(_={}));const Ni={[T.EBML]:{type:_.Master},[T.EBMLVersion]:{type:_.UnsignedInteger},[T.EBMLReadVersion]:{type:_.UnsignedInteger},[T.EBMLMaxIDLength]:{type:_.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[T.DocType]:{type:_.String},[T.DocTypeVersion]:{type:_.UnsignedInteger},[T.DocTypeReadVersion]:{type:_.UnsignedInteger},[T.Void]:{type:_.Binary},[T.Segment]:{type:_.Master},[T.SeekHead]:{type:_.Master},[T.Seek]:{type:_.Master},[T.SeekID]:{type:_.Binary},[T.SeekPosition]:{type:_.UnsignedInteger},[T.Info]:{type:_.Master},[T.TimestampScale]:{type:_.UnsignedInteger},[T.Duration]:{type:_.Float},[T.Tracks]:{type:_.Master},[T.TrackEntry]:{type:_.Master},[T.Video]:{type:_.Master},[T.Projection]:{type:_.Master},[T.ProjectionType]:{type:_.UnsignedInteger},[T.ProjectionPrivate]:{type:_.Master},[T.Chapters]:{type:_.Master},[T.Cluster]:{type:_.Master},[T.Timestamp]:{type:_.UnsignedInteger},[T.SilentTracks]:{type:_.Master},[T.SilentTrackNumber]:{type:_.UnsignedInteger},[T.Position]:{type:_.UnsignedInteger},[T.PrevSize]:{type:_.UnsignedInteger},[T.SimpleBlock]:{type:_.Binary},[T.BlockGroup]:{type:_.Master},[T.EncryptedBlock]:{type:_.Binary},[T.Attachments]:{type:_.Master},[T.Tags]:{type:_.Master},[T.Cues]:{type:_.Master},[T.CuePoint]:{type:_.Master},[T.CueTime]:{type:_.UnsignedInteger},[T.CueTrackPositions]:{type:_.Master},[T.CueTrack]:{type:_.UnsignedInteger},[T.CueClusterPosition]:{type:_.UnsignedInteger},[T.CueRelativePosition]:{type:_.UnsignedInteger},[T.CueDuration]:{type:_.UnsignedInteger},[T.CueBlockNumber]:{type:_.UnsignedInteger},[T.CueCodecState]:{type:_.UnsignedInteger},[T.CueReference]:{type:_.Master},[T.CueRefTime]:{type:_.UnsignedInteger}},cs=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=ai(a,t),s=i in Ni,r=s?Ni[i].type:_.Binary,n=a.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(a.buffer,a.byteOffset+t+1,o-1),d=n&255>>o,h=ai(c),u=d*2**((o-1)*8)+h,p=t+o;let f;return p+u>a.byteLength?f=new DataView(a.buffer,a.byteOffset+p):f=new DataView(a.buffer,a.byteOffset+p,u),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:r,tagHeaderSize:p,tagSize:p+u,value:f,valueSize:u}},ai=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ue=(a,e)=>{switch(e){case _.SignedInteger:return a.getInt8(0);case _.UnsignedInteger:return ai(a);case _.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(a);case _.UTF8:return new TextDecoder("utf-8").decode(a);case _.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case _.Master:return a;case _.Binary:return a;default:M(e)}},Et=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=cs(i);if(!e(s))return;s.type===_.Master&&Et(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},qa=a=>{if(a.getUint32(0)!==T.EBML)return!1;let e,t,i;const s=cs(a);return Et(s.value,({tag:r,type:n,value:o})=>(r===T.EBMLReadVersion?e=Ue(o,n):r===T.DocType?t=Ue(o,n):r===T.DocTypeReadVersion&&(i=Ue(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},us=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],za=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],Wa=a=>{let e,t,i,s,r=!1,n=!1,o=!1,c,d,h=!1;const u=0;return Et(a,({tag:p,type:f,value:b,valueSize:E})=>{if(p===T.SeekID){const v=Ue(b,f);d=ai(v)}else p!==T.SeekPosition&&(d=void 0);return p===T.Segment?(e=b.byteOffset,t=b.byteOffset+E):p===T.Info?r=!0:p===T.SeekHead?n=!0:p===T.TimestampScale?i=Ue(b,f):p===T.Duration?s=Ue(b,f):p===T.SeekPosition&&d===T.Cues?c=Ue(b,f):p===T.Tracks?Et(b,({tag:v,type:R,value:N})=>v===T.ProjectionType?(h=Ue(N,R)===1,!1):!0):r&&n&&us.includes(p)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:u,projectionType:si.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Qa=a=>{if(J(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ja=(a,e)=>{let t=!1,i=!1;const s=o=>w(o.time)&&w(o.position),r=[];let n;return Et(a,({tag:o,type:c,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&s(n)&&r.push(n),n={};break;case T.CueTime:n&&(n.time=Ue(d,c));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=Ue(d,c));break;default:t&&us.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&r.push(n),r.map((o,c)=>{const{time:d,position:h}=o,u=r[c+1];return{status:j.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Ja=a=>{let e=0,t=!1;try{Et(a,i=>i.tag===T.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):za.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Xa={validateData:qa,parseInit:Wa,getIndexRange:Qa,parseSegments:ja,parseFeedableSegmentChunk:Ja},hs=1e4,Ka=3e4,Za=5e3,er=hs,tr=({id:a,width:e,height:t,bitrate:i,fps:s,quality:r})=>{const n=(r?Vt(r):void 0)??pt({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},ir=({id:a,bitrate:e})=>({id:a,bitrate:e}),sr=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},ar=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),jt=a=>{const e=[];let t=0,i=a.length-1;for(;t<hs&&i>=0;)e.unshift(a[i]),t+=a[i].time.to-a[i].time.from,i--;return e};class Oi{onLastSegment$=new m(!1);fullyBuffered$=new m(!1);playingRepresentation$=new m(void 0);playingRepresentationInit$=new m(void 0);error$=new x;gaps=[];isSeekingLive=!1;subscription=new te;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new AbortController;destroyAbortController=new AbortController;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;constructor(e,t,i,s,{fetcher:r,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1,manifest:d}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!d?.dynamic,this.container=i,i){case vt.MP4:this.containerParser=Ga;break;case vt.WEBM:this.containerParser=Xa;break;default:M(i)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=Pe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);P(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ea(this.sourceBuffer),this.subscription.add(L(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(L(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.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,Mi(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),r=this.parsedInitData.get(t.id);P(i,"No init buffer for starting representation"),P(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(r))}.bind(this));switchTo=Pe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);P(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(J(s)||J(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),P(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const r=this.getCurrentPosition();w(r)&&(this.searchGaps(i,t),this.maintain(r))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(d=>e>=d.time.from&&e<d.time.to);let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=rt(this.sourceBuffer.buffered,e),u=s?s.time.to+100:-1/0;s&&h>=s.time.to-e+100&&(r=u)}if(isFinite(this.bufferLimit)&&Mi(this.sourceBuffer.buffered)>=this.bufferLimit){const d=rt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,r),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))d="high";else{const h=o.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===j.FED&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=i.at(-1);c&&c.status===j.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let i=0;for(const s of e)s.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from}),i=s.time.to;w(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=Pe(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const c=e.find(u=>u.id===o);c&&this.representations.set(o,c);const d=this.representations.get(o);if(!d)return;const h=jt(d.segmentReference.segments);this.segments.set(d.id,h)}const t=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,i=this.representations.get(t);P(i);const s=jt(i.segmentReference.segments),r=this.initData.get(i.id);if(P(r,"No init buffer for starting representation"),P(s,"No segments for starting representation"),!(r instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t)return;const i=t.segmentReference.segments.map(o=>({...o,status:j.NONE,size:void 0})),s=this.segments.get(t.id)??[],r=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.round(r)>=Math.round(o.time.from)&&Math.round(r)<=Math.round(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=jt(i);this.segments.set(t.id,[...o])}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(r=>r.time.from<=e&&r.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:u,time:{from:p,to:f}},b)=>{const E=p<=i&&f>=i,v=p>i||E||b===0&&i===0,R=Math.min(this.forwardBufferTarget,this.bufferLimit),N=this.preloadOnly&&p<=i+R||f<=i+R;return(u===j.NONE||u===j.PARTIALLY_EJECTED&&v&&N&&this.sourceBuffer&&!yi(this.sourceBuffer.buffered,i))&&v&&N});if(s===-1)return[];if(t!==Le.BYTE_RANGE)return e.slice(s,s+1);const r=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let u=s;u<r.length&&(n<=d||o<=h);u++){const p=r[u];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status===j.NONE||p.status===j.PARTIALLY_EJECTED)c.push(p);else break}return c}async loadSegments(e,t,i="auto"){if(!e.length)return;let s,r,n=e;const{type:o}=t.segmentReference;switch(o){case Le.BYTE_RANGE:{s=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Le.TEMPLATE:{const d=e.at(0);s=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:M(o)}for(const d of n)d.status=j.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await Pe(c,async function*(){const d=_i(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(s,{range:r,onProgress:(d,h)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,r?r.from:0,h,c)}catch(u){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:c,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(d)}})}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&w(i)&&(t=rt(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:C.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,s,r){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=u=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),u.segment.status=j.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const f of this.segments.get(p.id)??[])f.status===j.FED&&f.time.from===u.segment.time.from&&f.time.to===u.segment.time.to&&(f.status=j.NONE);this.activeSegments.delete(u),this.detectGapsWhenIdle(t,[u.segment])},c=this.representations.get(t);if(!c)return;const d=c.segmentReference.type,h=e.byteLength;for(const u of this.activeSegments){const{segment:p}=u,f=d===Le.BYTE_RANGE,b=f?p.byte.to-p.byte.from+1:h;if(u.representationId!==t||!(!f||p.byte.from>=i&&p.byte.to<i+e.byteLength))continue;if(r.aborted){n();continue}const v=f?p.byte.from-i:0,R=f?p.byte.to-i:e.byteLength,N=v<s,g=R<=s;if(p.status===j.DOWNLOADING&&N&&g){p.status=j.DOWNLOADED,this.activeSegments.delete(u);const $=new DataView(e.buffer,e.byteOffset+v,b);this.sourceBufferTaskQueue.append($,r).then(k=>k&&!r.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&N&&(u.loadedBytes=Math.min(b,s-v),u.loadedBytes>u.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+v+u.feedingBytes,u.loadedBytes-u.feedingBytes),k=u.loadedBytes===b?$:this.containerParser.parseFeedableSegmentChunk($);k?.byteLength&&(p.status=j.PARTIALLY_FED,u.feedingBytes+=k.byteLength,this.sourceBufferTaskQueue.append(k,r).then(O=>{if(r.aborted)n();else if(O)u.fedBytes+=k.byteLength,u.fedBytes===b&&o(u);else{if(u.feedingBytes<b)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=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?Pe(this.destroyAbortController.signal,async function*(){const o=_i(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:c,dataView:d,segments:h}=o,u=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,u),this.segments.set(e.id,this.isLive?jt(h):h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||J(e)||this.sourceBuffer.updating)return!1;let s=0,r=1/0,n=-1/0,o=!1;const c=d=>{r=Math.min(r,d.time.from),n=Math.max(n,d.time.to);const h="size"in d?d.size??0:d.byte.to-d.byte.from;s+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===j.FED&&c(h)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=1/0,n=-1/0;for(const d of this.segments.values())for(const h of d){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===j.FED&&c(h)}}if(o=isFinite(r)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const h=this.sourceBuffer.buffered.start(d)*1e3,u=this.sourceBuffer.buffered.end(d)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===j.NONE&&Math.round(f.time.from)<=Math.round(h)&&Math.round(f.time.to)>=Math.round(u)){r=h,n=u;break}}if(o=isFinite(r)&&isFinite(n),!o&&i){s=0,r=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const u of h)u.time.from>e+d&&u.status===j.FED&&c(u)}return o=isFinite(r)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(r,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){const n=this.sourceBuffer.buffered.start(r)*1e3,o=this.sourceBuffer.buffered.end(r)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(r=>s&&r.from===s.from&&r.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:C.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(J(this.sourceBuffer)||J(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),r=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:r})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:r}=s;if(r!==j.FED&&r!==j.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),c=e.some(h=>h.from-t<=n&&h.to+t>=o),d=e.filter(h=>n>=h.from-t&&n<=h.to+t||o>=h.from-t&&o<=h.to+t);c||(d.length===1?s.status=j.PARTIALLY_EJECTED:s.status=j.NONE)}}}var bt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(bt||(bt={}));class rr{throughputEstimator;requestQuic;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);abortAllController=new AbortController;subscription=new te;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=rs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=Pe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=yt(t));const i=yield fetch(t,{signal:this.abortAllController.signal}).catch(xt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=Pe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?bt.HEADER:bt.PARAM,range:i,onProgress:s,priority:r="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(i)switch(t){case bt.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case bt.PARAM:{const A=new URL(c,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),c=A.toString();break}default:M(t)}this.requestQuic&&(c=yt(c));let h=this.abortAllController.signal,u;if(n){const A=new AbortController;if(u=B(L(this.abortAllController.signal,"abort"),L(n,"abort")).subscribe(()=>{try{A.abort()}catch(F){xt(F)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(F){xt(F)}h=A.signal}const p=ue(),f=yield fetch(c,{priority:r,headers:d,signal:h}).catch(xt),b=ue();if(this.throughputEstimator?.addRawRtt(b-p),!f)return u?.unsubscribe(),null;if(!f.ok||!f.body)return u?.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const E=parseInt(f.headers.get("Content-Length")??"",10)||i&&i.to-i.from+1||NaN;if(!E){const A=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(A.byteLength,ue()-b),s?.(new DataView(A),A.byteLength),u?.unsubscribe(),A}if(!s&&!o)return u?.unsubscribe(),f.arrayBuffer();const[v,R]=f.body.tee(),N=v.getReader();o&&this.throughputEstimator?.trackStream(R);let g=0;const $=new ArrayBuffer(E),k=new Uint8Array($),O=new DataView($);let W=!1;const G=A=>{u?.unsubscribe(),W=!0,xt(A)},Q=Pe(h,async function*({done:A,value:F}){if(g===0&&this.lastRequestFirstBytes$.next(ue()-p),h.aborted){u?.unsubscribe();return}!A&&F&&(k.set(F,g),g+=F.byteLength,s?.(O,g),yield N?.read().then(Q,G))}.bind(this));return yield N?.read().then(Q,G),u?.unsubscribe(),W?null:$}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Le.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Le.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:M(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=Pe(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Le.BYTE_RANGE)return null;const{from:s,to:r}=e.initRange;let n=s,o=r,c=!1,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,c=r+1===d,c&&(n=Math.min(d,s),o=Math.max(h,r))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!u)return null;const p=new DataView(u,s-n,r-n+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),b=e.indexRange??t.getIndexRange(f);if(!b)throw new ReferenceError("No way to load representation index");let E;if(c)E=new DataView(u,b.from-n,b.to-b.from+1);else{const R=yield this.fetch(e.url,{range:b,priority:i,measureThroughput:!1});if(!R)return null;E=new DataView(R)}const v=t.parseSegments(E,f,b);return{init:f,dataView:new DataView(u),segments:v}}.bind(this));fetchTemplateRepresentation=Pe(this.abortAllController.signal,async function*(e,t){if(e.type!==Le.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(n=>({...n,status:j.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const xt=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},Fi=a=>{if(!a.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),s=i?.[1]==="-"?-1:1,r={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},mi=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,r]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>J(r)?o:J(c)?r:r.padStart(parseInt(c,10),"0"))}return t},nr=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},r=i.children[0],n=r.getElementsByTagName("Period")[0],o=n.children,c=r.getAttribute("type")==="dynamic",d=r.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let u;const p=r.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),E=r.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)u=Fi(p);else if(f){const g=Fi(f);w(g)&&(u=g)}else E&&(u=parseInt(E,10));let v=0;const R=r.getAttribute("profiles")?.split(",")??[],N=R.includes(ii.WEBM_AS_IN_FFMPEG)||R.includes(ii.WEBM_AS_IN_SPEC)?vt.WEBM:vt.MP4;for(const g of o){const $=g.getAttribute("mimeType"),k=g.getAttribute("codecs"),O=g.getAttribute("contentType")??$?.split("/")[0],W=g.getAttribute("profiles")?.split(",")??[],G=g.querySelectorAll("Representation"),Q=g.querySelector("SegmentTemplate");if(O===Se.TEXT){for(const A of G){const F=A.getAttribute("id")||"",q=g.getAttribute("lang"),ie=A.querySelector("BaseURL")?.textContent?.trim()??"",be=new URL(ie,e).toString();s[Se.TEXT].push({id:F,lang:q,kind:Se.TEXT,url:be})}continue}for(const A of G){const F=A.getAttribute("mimeType")??$,q=A.getAttribute("codecs")??k??"",ie=A.getAttribute("contentType")??F?.split("/")[0]??O,be=g.getAttribute("profiles")?.split(",")??[],_e=parseInt(A.getAttribute("width")??"",10),I=parseInt(A.getAttribute("height")??"",10),ee=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,he=A.getAttribute("frameRate")??"",me=A.getAttribute("quality")??void 0,ke=he?Ai(he):void 0,tt=A.getAttribute("id")??(v++).toString(10),ui=ie==="video"?`${I}p`:ie==="audio"?`${ee}Kbps`:q,Ht=`${tt}@${ui}`,Z=A.querySelector("BaseURL")?.textContent?.trim()??"",ve=new URL(Z,e).toString(),xe=[...R,...W,...be];let Ae;const dt=A.querySelector("SegmentBase"),Be=A.querySelector("SegmentTemplate")??Q;if(dt){const Oe=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[We,mt]=Oe.split("-").map(gt=>parseInt(gt,10)),At={from:We,to:mt},wt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[hi,Yt]=wt?wt.split("-").map(gt=>parseInt(gt,10)):[],Pt=wt?{from:hi,to:Yt}:void 0;Ae={type:Le.BYTE_RANGE,url:ve,initRange:At,indexRange:Pt}}else if(Be){const Oe={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},We=parseInt(Be.getAttribute("timescale")??"",10),mt=Be.getAttribute("initialization")??"",At=Be.getAttribute("media"),wt=parseInt(Be.getAttribute("startNumber")??"",10)??1,hi=mi(mt,Oe);if(!At)throw new ReferenceError("No media attribute in SegmentTemplate");const Yt=Be.querySelectorAll("SegmentTimeline S")??[],Pt=[];let gt=0;if(Yt.length){let li=wt,Qe=0;for(const Dt of Yt){const it=parseInt(Dt.getAttribute("d")??"",10),ct=parseInt(Dt.getAttribute("r")??"",10)||0,Gt=parseInt(Dt.getAttribute("t")??"",10);Qe=Number.isFinite(Gt)?Gt:Qe;const pi=it/We*1e3,Pi=Qe/We*1e3;for(let qt=0;qt<ct+1;qt++){const Ts=mi(At,{...Oe,segmentNumber:li.toString(10),segmentTime:(Qe+qt*it).toString(10)}),Di=(Pi||0)+qt*pi,ys=Di+pi;li++,Pt.push({time:{from:Di,to:ys},url:Ts})}Qe+=(ct+1)*it,gt+=(ct+1)*pi}}else if(w(u)){const Qe=parseInt(Be.getAttribute("duration")??"",10)/We*1e3,Dt=Math.ceil(u/Qe);let it=0;for(let ct=1;ct<Dt;ct++){const Gt=mi(At,{...Oe,segmentNumber:ct.toString(10),segmentTime:it.toString(10)});Pt.push({time:{from:it,to:it+Qe},url:Gt}),it+=Qe}}Ae={type:Le.TEMPLATE,baseUrl:ve,initUrl:hi,totalSegmentsDurationMs:gt,segments:Pt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!F)continue;const ze={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[ie];ze&&s[ze].push({id:Ht,kind:ze,segmentReference:Ae,profiles:xe,duration:u,bitrate:ee,mime:F,codecs:q,width:_e,height:I,fps:ke,quality:me})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:u,container:N,representations:s}},vi=1e3,Vi=["timeupdate","progress","play","seeked","stalled","waiting"];var Ce;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Ce||(Ce={}));let or=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new te;representationSubscription=new te;fetcher;state$=new ne(Ce.NONE);currentVideoRepresentation$=new m(void 0);currentVideoRepresentationInit$=new m(void 0);error$=new x;lastConnectionType$=new m(void 0);lastConnectionReused$=new m(void 0);lastRequestFirstBytes$=new m(void 0);isLive$=new m(!1);liveDuration$=new m(0);liveAvailabilityStartTime$=new m(void 0);bufferLength$=new m(0);liveLoadBufferLength$=new m(0);forceEnded$=new x;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new rr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=Pe(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Ye(t,i,fe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ce.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Ce.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=Pe(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:C.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return this.manifest;let t;try{t=nr(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:C.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:r,codecs:n})=>!!(this.element?.canPlayType?.(r)&&window.MediaSource?.isTypeSupported?.(`${r}; codecs="${n}"`)||s===Se.TEXT);return this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,r])=>[s,r.filter(i)]))}}.bind(this));async seekLive(e){P(this.element),this.manifestUrlString=Ye(this.manifestUrlString,e,fe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio)}initRepresentations=Pe(this.destroyController.signal,async function*(e,t){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ce.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Oi(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],w(t)&&(this.audioBufferManager=new Oi(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Zt(vi).subscribe(n=>{if(this.element?.paused){const o=xi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ye(this.manifestUrlString,o+1e3,fe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(B(...Vi.map(n=>L(this.element,n))).pipe(ks(vi),y(n=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(o=>{let c=0;if(o){const d=(this.element?.currentTime??0)*1e3;c=Math.min(...this.bufferManagers.map(u=>u.getLiveSegmentsToLoadState(this.manifest)?.to??0))-d}this.liveLoadBufferLength$.next(c)}));let n=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async o=>{P(this.element);const c=this.element.playbackRate,d=xi(this.manifestUrlString,fe.DASH_CMAF_OFFSET_P),h=Ka*c,u=er*c,p=Za*c;n=o>n?o:n;const f=d===0&&o<p,b=d!==0&&o<h+p&&o>=h,E=d!==0&&o<h;if(E||b){const v=n-(h+u),R=Math.trunc(d+v/c);let N;o?R>0?N=R:N=0:N=d,this.manifestUrlString=Ye(this.manifestUrlString,N,fe.DASH_CMAF_OFFSET_P)}(f||E||b)&&(await this.updateLive(),n=0)}))}const s=B(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(y(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),r=B(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(y(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.representationSubscription.add(B(this.forceEnded$,De({allBuffersFull:s,someBufferEnded:r}).pipe(K(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.representationSubscription.add(B(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(n=>this.source?.addEventListener("sourceopen",n))),w(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&w(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Ce.REPRESENTATIOS_READY)}.bind(this));initBuffer(){P(this.element),this.state$.setState(Ce.RUNNING),this.subscription.add(B(...Vi.map(e=>L(this.element,e)),L(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(L(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(L(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e]?.switchTo(t)}seek(e,t){P(this.element),P(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),yi(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ce.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Zt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.manifest=await this.updateManifest(),this.bufferManagers?.forEach(e=>e.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const r of s.gaps)s.playingRepresentation$.getValue()===r.representation&&r.from<=t&&r.to>t&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?i.push(1/0):i.push(r.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};class dr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class cr{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,r=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:s,y:r,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var ur=`#define GLSLIFY 1
30
+ attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,hr=`#ifdef GL_ES
31
31
  precision highp float;precision highp int;
32
32
  #else
33
33
  precision highp float;
34
34
  #define GLSLIFY 1
35
35
  #endif
36
36
  #define PI 3.14159265358979323846264
37
- 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 kr{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 vr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Er(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"),r=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(r,-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($r,this.gl.VERTEX_SHADER),i=this.createShader(Ar,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,r=e-i,n=t-s,o=e+i,c=t-s,d=e+i,h=t+s,u=e-i,p=t+s;return[r,n,o,c,d,h,u,p]}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}}class bs{scene3D;subscription=new te;videoState=new oe(de.STOPPED);video;player;params;elementSize$=new f(void 0);textTracksManager=new je;droppedFramesManager=new li;videoTracks$=new f([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new aa;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=et(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(Ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Tr({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=it(this.video),s=this.constructor.name,r=o=>{e.error$.next({id:s,category:R.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:(o,c)=>this.subscription.add(o.subscribe(c,r))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:r}=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(v(d=>d.map(({track:h})=>h)))}),r(i.ended$,e.endedEvent$),r(i.looped$,e.loopedEvent$),r(i.error$,e.error$),r(i.isBuffering$,e.isBuffering$),r(i.currentBuffer$,e.currentBuffer$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.inPiP$,e.inPiP$),r(i.inFullscreen$,e.inFullscreen$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.isLive$,e.isLive$),r(this.player.lastRequestFirstBytes$.pipe(J(A),le()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(bt(this.video,t.isLooped,s)),this.subscription.add(Ze(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ct(this.video,t.playbackRate,i.playbackRateState$,s)),r(si(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),D(t.playbackState,l.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),D(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Ce.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();w(u,"Manifest not loaded or empty");const p=Array.from(u.audio).sort((T,_)=>_.bitrate-T.bitrate),S=Array.from(u.video).sort((T,_)=>_.bitrate-T.bitrate),b=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const T of p){const _=ur(T);_&&this.audioTracks.push({track:_,representation:T})}for(const T of S){const _=hr(T);if(_){h.push({track:_,representation:T});const G=!this.params.tuning.isAudioDisabled&&lr(p,S,T);G&&this.audioRepresentations.set(T.id,G)}}this.videoTracks$.next(h);for(const T of b){const _=pr(T);_&&this.textTracks.push({track:_,representation:T})}this.params.output.availableVideoTracks$.next(h.map(({track:T})=>T)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:T})=>T)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:T})=>T));const $=this.selectVideoRepresentation();w($),this.player.initRepresentations($.id,this.audioRepresentations.get($.id)?.id)}else d===Ce.REPRESENTATIOS_READY&&(this.videoState.setState(de.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(M(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,C(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Ce.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();if(p&&this.params.output.autoVideoTrackLimits$.next(p.to),u){this.player.switchRepresentation(Se.VIDEO,u.id).catch(n);const S=this.audioRepresentations.get(u.id);S&&this.player.switchRepresentation(Se.AUDIO,S.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(he(),v(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(v(({to:d})=>d===l.READY),he());this.subscription.add(M(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===l.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(M(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===l.READY)));const c=M(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(Be(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),i=this.videoTracks$.getValue().find(({track:{id:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),r=dt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(r/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=Lt(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===Y.Requested&&i?.to!==l.PAUSED&&e!==de.STOPPED&&t!==l.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===l.STOPPED){e!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}switch(e){case de.STOPPED:this.videoState.startTransitionTo(de.READY),this.prepare();return;case de.READY:t===l.PAUSED?(this.videoState.setState(de.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):i?.to===l.READY&&D(this.params.desiredState.playbackState,l.READY);return;case de.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case de.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(de.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===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return O(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new kr(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(){ht(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(de.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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),tt(this.video)}}class wr extends bs{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)}}class Pr extends bs{constructor(e){super(e),this.liveOffset=new ui}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($e({interval:ii(Di),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===de.PLAYING&&!this.player.isActiveLowLatency){const r=e.position$.getValue()+(s-1);e.position$.next(r),this.liveOffset?.resetTo(-r*1e3)}})).add($e({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(v(({liveBufferTime:s,liveAvailabilityStartTime:r})=>s&&r?s+r: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===l.PAUSED&&i===de.PAUSED,r=-e,n=Math.trunc(r/1e3<=Math.abs(this.params.output.duration$.getValue())?r:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const Ye={};var X;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(X||(X={}));const Bt=(a,e)=>new hi(t=>{const i=(s,r)=>t.next(r);return a.on(e,i),()=>a.off(e,i)});class Dr{subscription=new te;videoState=new oe(X.INITIALIZING);video;params;hls;textTracksManager=new je;trackLevels=new Map;constructor(e){this.video=et(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(Ae(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),tt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.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||(Ye.Hls=s.default,Ye.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){w(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){w(Ye.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},s=it(this.video),r=(d,h)=>this.subscription.add(d.subscribe(h,i));r(s.timeUpdate$,t.position$),r(s.durationChange$,t.duration$),r(s.ended$,t.endedEvent$),r(s.looped$,t.loopedEvent$),r(s.error$,t.error$),r(s.isBuffering$,t.isBuffering$),r(s.currentBuffer$,t.currentBuffer$),r(s.loadStart$,t.firstBytesEvent$),r(s.playing$,t.firstFrameEvent$),r(s.canplay$,t.canplay$),r(s.seeked$,t.seekedEvent$),r(s.inPiP$,t.inPiP$),r(s.inFullscreen$,t.inFullscreen$),this.subscription.add(bt(this.video,e.isLooped,i)),this.subscription.add(Ze(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ct(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(Bt(this.hls,Ye.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.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(X.PLAYING),D(e.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),D(e.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===X.READY&&this.videoState.setState(X.READY),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},i)),r(Bt(this.hls,Ye.Events.MANIFEST_PARSED).pipe(v(({levels:d})=>d.reduce((h,u)=>{const p=u.name||u.height.toString(10),{width:S,height:b}=u,$=Gt(u.attrs.QUALITY??"")??St({width:S,height:b});if(!$)return h;const T=u.attrs["FRAME-RATE"]?parseFloat(u.attrs["FRAME-RATE"]):void 0,_={id:p.toString(),quality:$,bitrate:u.bitrate/1e3,size:{width:S,height:b},fps:T};return this.trackLevels.set(p,{track:_,level:u}),h.push(_),h},[]))),t.availableVideoTracks$),r(Bt(this.hls,Ye.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const h=[];for(const u of d.subtitleTracks){const p=u.name,S=u.attrs.URI||"",b=u.lang,$="internal";h.push({id:p,url:S,language:b,type:$})}e.internalTextTracks.startTransitionTo(h)}}),r(Bt(this.hls,Ye.Events.LEVEL_LOADING).pipe(v(({url:d})=>Ae(d))),t.hostname$),this.subscription.add(Ue(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=Bt(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(v(({level:d})=>n(this.hls.levels[d])));o.pipe(J(A)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ue(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel])?.id,d=>{if(j(d))return;const h=this.trackLevels.get(d)?.level;if(!h)return;const u=this.hls.levels.indexOf(h),p=this.hls.currentLevel,S=this.hls.levels[p];!S||h.bitrate>S.bitrate?this.hls.nextLevel=u:(this.hls.loadLevel=u,this.hls.loadLevel=u)},{changed$:o.pipe(v(d=>d?.id)),onError:i})),r(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=M(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,De(["init"])).pipe(Be(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!==X.INITIALIZING)switch(i?.to!==l.PAUSED&&s.state===Y.Requested&&this.seek(s.position),t){case l.STOPPED:switch(e){case X.STOPPED:break;case X.READY:case X.PLAYING:case X.PAUSED:this.stop();break;default:O(e)}break;case l.READY:switch(e){case X.STOPPED:this.prepare();break;case X.READY:case X.PLAYING:case X.PAUSED:break;default:O(e)}break;case l.PLAYING:switch(e){case X.PLAYING:break;case X.STOPPED:this.prepare();break;case X.READY:case X.PAUSED:this.playIfAllowed();break;default:O(e)}break;case l.PAUSED:switch(e){case X.PAUSED:break;case X.STOPPED:this.prepare();break;case X.READY:this.videoState.setState(X.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED);break;case X.PLAYING:this.pause();break;default:O(e)}break;default:O(t)}};prepare(){this.videoState.startTransitionTo(X.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(X.PLAYING),await ht(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t}))||(this.videoState.setState(X.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))}pause(){this.videoState.startTransitionTo(X.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(X.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0)}}const Qi="X-Playback-Duration";var ji=async a=>{const e=await fetch(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Qi)?parseInt(e.headers.get(Qi),10):void 0};const xr=a=>{let e=null;if(a.QUALITY&&(e=Gt(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=St({width:t,height:i})}return e??null},ys=async(a,e=a)=>{const s=(await(await fetch(a)).text()).split(`
38
- `),r=[];for(let n=0;n<s.length;n++){const c=s[n].match(/^#EXT-X-STREAM-INF:(.+)/);if(!c)continue;const d=Object.fromEntries(c[1].split(",").map(T=>T.split("="))),h=d.QUALITY??`stream-${d.BANDWIDTH}`,u=xr(d);let p;d.BANDWIDTH&&(p=parseInt(d.BANDWIDTH,10)/1e3||void 0),!p&&d["AVERAGE-BANDWIDTH"]&&(p=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const S=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let b;if(d.RESOLUTION){const[T,_]=d.RESOLUTION.split("x").map(G=>parseInt(G,10));T&&_&&(b={width:T,height:_})}const $=new URL(s[++n],e).toString();u&&r.push({id:h,quality:u,url:$,bandwidth:p,size:b,fps:S})}return r};var se;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(se||(se={}));class Lr{subscription=new te;videoState=new oe(se.STOPPED);video;params;textTracksManager=new je;manifests$=new f([]);maxSeekBackTime$;liveOffset=new ui;manifestStartTime$=new f(void 0);constructor(e){this.params=e,this.video=et(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Re.INVARIANT,url:this.params.source.url};ys(Qe(this.params.source.url),this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(Ae(this.params.source.url)),this.maxSeekBackTime$=new f(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),r=s?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=it(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,i));r(s.ended$,e.endedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ze(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),D(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),D(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(he(),v(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&&A(d.to)){const u=d.to;this.params.desiredState.videoTrack.setState(u);const p=this.manifests$.getValue().find(S=>S.id===u);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Ae(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===se.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===Y.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($e({startTime:this.manifestStartTime$.pipe(J(A)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),i)),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:p})=>({id:c,quality:d,size:h,fps:p,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i));const n=M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,De(["init"])).pipe(Be(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){const e=this.selectManifest();if(j(e))return;const t=this.params.format===g.HLS_LIVE_CMAF?fe.DASH_CMAF_OFFSET_P:fe.OFFSET_P,i=Qe(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),ji(i).then(s=>{if(!j(s))this.maxSeekBackTime$.next(s);else{const r=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(j(r)||!isFinite(r))try{fetch(i).then(n=>n.text()).then(n=>{const o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n)?.[1];if(o){const c=new URL(o,i).toString();ji(c).then(d=>{j(d)||this.maxSeekBackTime$.next(d)})}})}catch{}}})}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===l.STOPPED){t!==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),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(r||n){const d=this.videoState.getState();this.videoState.setState(se.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==l.PAUSED&&c.state===Y.Requested){this.videoState.startTransitionTo(se.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case se.READY:i===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case se.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(se.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)):this.seek(-this.liveOffset.getTotalOffset())):s?.to===l.PAUSED&&(D(this.params.desiredState.playbackState,l.PAUSED),this.liveOffset.pause());return;case se.CHANGING_MANIFEST:break;default:return O(t)}}}var ne;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(ne||(ne={}));class _r{subscription=new te;videoState=new oe(ne.STOPPED);video;params;textTracksManager=new je;manifests$=new f([]);constructor(e){this.params=e,this.video=et(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Re.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(Ae(this.params.source.url)),ys(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),r=s?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},s=it(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ze(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),D(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),D(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.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&&A(d.to)){const u=d.to;this.params.desiredState.videoTrack.setState(u);const p=this.manifests$.getValue().find(S=>S.id===u);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Ae(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===ne.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===Y.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:p})=>({id:c,quality:d,size:h,fps:p,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i));const n=M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,De(["init"])).pipe(Be(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),tt(this.video)}prepare(){const e=this.selectManifest();j(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===l.STOPPED){t!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(r||n){const d=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:h}=this.video;this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&c.state===Y.Requested&&this.seek(c.position),t){case ne.READY:i===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(ne.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case ne.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;case ne.CHANGING_MANIFEST:break;default:return O(t)}}}var ce;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ce||(ce={}));class Rr{subscription=new te;videoState=new oe(ce.STOPPED);video;trackUrls={};params;textTracksManager=new je;constructor(e){this.params=e,this.video=et(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const r=s.toString(10);this.trackUrls[r]={track:{quality:t,id:r},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:R.WTF,message:"MpegProvider internal logic error",thrown:o})},s=it(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,i));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ze(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),D(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),D(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ce.READY&&this.videoState.setState(ce.READY);const o=this.params.desiredState.videoTrack.getTransition();o&&A(o.to)&&(this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to].track)),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=M(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,De(["init"])).pipe(Be(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),tt(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();w(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];w(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ae(t))}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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===l.STOPPED){e!==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),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(r&&e!==ce.READY&&!n){this.handleQualityLimitTransition(r.to.max);return}if(e===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(n){const{currentTime:c}=this.video;this.prepare(),o.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==l.PAUSED&&o.state===Y.Requested&&this.seek(o.position),e){case ce.READY:t===l.READY?D(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(ce.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):i?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case ce.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return O(e)}};handleQualityLimitTransition(e){let t;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const i=Object.values(this.trackUrls).find(n=>os(n.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState(),r=this.trackUrls[s??"0"]?.track;i&&r&&Ei(r.quality,i.quality)&&(t=i)}else if(!e){const i=Object.values(this.trackUrls).map(s=>s.track);t=Lt(i,{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.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const Ji=["stun:videostun.mycdn.me:80"],Cr=1e3,Ir=3,vi=()=>null;class Br{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=vi;externalStopCallback=vi;externalErrorCallback=vi;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:Ji}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:R.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),Cr)}normalizeOptions(e={}){const t={stunServerList:Ji,maxRetryNumber:Ir,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ae;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ae||(ae={}));class Mr{subscription;params;log;video;videoState=new oe(ae.STOPPED);liveStreamClient;maxSeekBackTime$=new f(0);constructor(e){this.subscription=new te,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=et(e.container),this.liveStreamClient=new Br(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),tt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};M(this.videoState.stateChangeStarted$.pipe(v(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=it(this.video),r=(n,o)=>this.subscription.add(n.subscribe(o,i));r(s.timeUpdate$,e.liveTime$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(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===ae.READY&&this.videoState.setState(ae.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ze(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ae.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(l.STOPPED);break;case ae.READY:break;case ae.PAUSED:t.playbackState.setState(l.PAUSED);break;case ae.PLAYING:t.playbackState.setState(l.PLAYING);break;default:return O(n.to)}},i)).add(M(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,De(["init"])).pipe(Be(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(Ae(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:Re.INVARIANT}),this.video.srcObject=e,D(this.params.desiredState.playbackState,l.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ae.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.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===l.STOPPED){e!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition();if(e===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(r){this.prepare();return}switch(e){case ae.READY:t===l.PAUSED?(this.videoState.setState(ae.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed());return;case ae.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),this.video.pause()):i?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case ae.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return O(e)}}}class Xi{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 Ts=Li().device===Ls.Android,ci=document.createElement("video"),Or='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Nr='video/mp4; codecs="hev1.1.6.L93.B0"',vs='video/webm; codecs="vp09.00.10.08"',Es='video/webm; codecs="av01.0.00M.08"',Fr='audio/mp4; codecs="mp4a.40.2"',Vr='audio/webm; codecs="opus"',Ve={mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(ci.canPlayType?.("application/x-mpegurl")||ci.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Pe={mp4:!!ci.canPlayType?.("video/mp4"),webm:!!ci.canPlayType?.("video/webm"),cmaf:!0},We={h264:!!window.MediaSource?.isTypeSupported?.(Or),h265:!!window.MediaSource?.isTypeSupported?.(Nr),vp9:!!window.MediaSource?.isTypeSupported?.(vs),av1:!!window.MediaSource?.isTypeSupported?.(Es),aac:!!window.MediaSource?.isTypeSupported?.(Fr),opus:!!window.MediaSource?.isTypeSupported?.(Vr)},$t=(We.h264||We.h265)&&We.aac;var ot;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(ot||(ot={}));var Ke;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg"})(Ke||(Ke={}));let ft;const Ur=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Es}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:vs}})]);ft={[g.DASH_WEBM_AV1]:e,[g.DASH_WEBM]:t}};try{Ur()}catch(a){console.error(a)}const Yt=Ve.hls&&Pe.mp4,Hr=()=>Object.keys(We).filter(a=>We[a]),Yr=(a,e=!1)=>a.filter(t=>{switch(t){case g.DASH:return Ve.mse&&Pe.mp4&&$t;case g.DASH_SEP:return Ve.mse&&Pe.mp4&&$t;case g.DASH_WEBM:return Ve.mse&&Pe.webm&&We.vp9&&We.opus;case g.DASH_WEBM_AV1:return Ve.mse&&Pe.webm&&We.av1&&We.opus;case g.DASH_LIVE:return Ve.mse&&Pe.mp4&&$t;case g.DASH_LIVE_CMAF:return Ve.mse&&Pe.mp4&&$t&&Pe.cmaf;case g.DASH_ONDEMAND:return Ve.mse&&Pe.mp4&&$t;case g.HLS:case g.HLS_ONDEMAND:return Yt||e&&Ve.mse&&Pe.mp4&&$t;case g.HLS_LIVE:case g.HLS_LIVE_CMAF:return Yt;case g.MPEG:return Pe.mp4;case g.DASH_LIVE_WEBM:return!1;case g.WEB_RTC_LIVE:return Ve.webrtc&&Ve.ws&&We.h264&&(Pe.mp4||Pe.webm);default:return O(t)}}),Mt=a=>{const e=g.DASH_WEBM,t=g.DASH_WEBM_AV1;switch(a){case ot.VP9:return[e,t];case ot.AV1:return[t,e];case ot.NONE:return[];case ot.SMOOTH:return ft?ft[t].smooth?[t,e]:ft[e].smooth?[e,t]:[t,e]:[e,t];case ot.POWER_EFFICIENT:return ft?ft[t].powerEfficient?[t,e]:ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:O(a)}return[e,t]},Gr=({webmCodec:a,androidPreferredFormat:e})=>{if(Ts)switch(e){case Ke.MPEG:return[g.MPEG,...Mt(a),g.DASH_SEP,g.DASH,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND];case Ke.HLS:return[g.HLS,g.HLS_ONDEMAND,...Mt(a),g.DASH_SEP,g.DASH,g.DASH_ONDEMAND,g.MPEG];case Ke.DASH:return[...Mt(a),g.DASH_SEP,g.DASH,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG]}return Yt?[...Mt(a),g.DASH_SEP,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG,g.DASH]:[...Mt(a),g.DASH_SEP,g.DASH,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG]},zr=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{const i=e?[g.DASH_LIVE_CMAF,g.DASH_LIVE]:[g.DASH_LIVE,g.DASH_LIVE_CMAF],s=e?[g.HLS_LIVE_CMAF,g.HLS_LIVE]:[g.HLS_LIVE,g.HLS_LIVE_CMAF],r=[...i,...s],n=[...s,...i];let o;if(Ts)switch(a){case Ke.DASH:{o=r;break}case Ke.HLS:case Ke.MPEG:{o=n;break}}else Yt?o=n:o=r;return t?[g.WEB_RTC_LIVE,...o]:[...o,g.WEB_RTC_LIVE]},Ki=a=>a?[g.HLS_LIVE,g.HLS_LIVE_CMAF,g.DASH_LIVE_CMAF]:[g.DASH_WEBM,g.DASH_WEBM_AV1,g.DASH_SEP,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG];var qr=a=>new hi(e=>{const t=new te,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(v(({from:d,to:h})=>`${d}-${h}`)),s=a.desiredPlaybackState$.stateChangeEnded$,r=a.providerChanged$.pipe(v(({type:d})=>d!==void 0)),n=new L;let o=0,c="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(r.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Wr={cacheDuration:12e4},Qr={chunkDuration:5e3,maxParallelRequests:5};class jr{current$=new f({type:void 0});providerError$=new L;noAvailableProvidersError$=new L;providerOutput={position$:new f(0),duration$:new f(1/0),volume$:new f({muted:!1,volume:1}),currentVideoTrack$:new f(void 0),availableVideoTracks$:new f([]),availableAudioTracks$:new f([]),isAudioAvailable$:new f(!0),autoVideoTrackLimitingAvailable$:new f(!1),autoVideoTrackLimits$:new f(void 0),currentBuffer$:new f(void 0),isBuffering$:new f(!0),error$:new L,warning$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new f(void 0),isLowLatency$:new f(!1),canChangePlaybackSpeed$:new f(!0),liveTime$:new f(void 0),liveBufferTime$:new f(void 0),availableTextTracks$:new f([]),currentTextTrack$:new f(void 0),hostname$:new f(void 0),httpConnectionType$:new f(void 0),httpConnectionReused$:new f(void 0),inPiP$:new f(!1),inFullscreen$:new f(!1),element$:new f(void 0),availableSources$:new f(void 0),is3DVideo$:new f(!1)};subscription=new te;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Yr([...zr(this.params.tuning),...Gr(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>A(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let r=[];i?r=[i]:s.length?r=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:r=t,this.log({message:`Selected formats: ${r.join(" > ")}`}),this.screenFormatsIterator=new Xi(r);const n=[...Ki(!0),...Ki(!1)];this.chromecastFormatsIterator=new Xi(n.filter(o=>A(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(j(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:R.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!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.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 r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ye.SCREEN:return this.createScreenProvider(t);case ye.CHROMECAST:return this.createChromecastProvider(t);default:return O(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,r=this.providerOutput,n={container:i,source:null,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case g.DASH:{const o=this.applyFailoverHost(t[e]);return w(o),new wa({...n,source:o,config:Wr})}case g.DASH_SEP:case g.DASH_WEBM:case g.DASH_WEBM_AV1:case g.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return w(o),this.params.tuning.useDashJs?new Fi({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new wr({...n,source:o})}case g.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return w(o),this.params.tuning.useDashJsCMAF?new Fi({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new Pr({...n,source:o})}case g.HLS:case g.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return w(o),Yt||!this.params.tuning.useHlsJs?new _r({...n,source:o}):new Dr({...n,source:o})}case g.HLS_LIVE:case g.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return w(o),new Lr({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case g.MPEG:{const o=this.applyFailoverHost(t[e]);return w(o),new Rr({...n,source:o})}case g.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return w(o),new va({...n,source:o,config:{...Qr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case g.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return w(o),new Mr({container:i,source:o,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case g.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return w(o),new Hs({connection:o,meta:r,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()?ye.CHROMECAST:ye.SCREEN}chooseFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return O(e)}}skipFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.next();case ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return O(e)}}handleNoFormatsError(e){switch(e){case ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return O(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 r=new URL(s);return r.host=t,r.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,r])=>[s,i(r)]))}initProviderErrorHandling(){const e=new te;let t=!1,i=0;return e.add(M(this.providerOutput.error$,qr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(v(s=>({id:`ProviderHangup:${s}`,category:R.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(J(({to:r})=>r===l.PLAYING),le()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const r=this.current$.getValue().destination;if(r===ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ye.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===R.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(r??ye.SCREEN)}})),e}}const Jr=5e3,Zi="one_video_throughput",es="one_video_rtt",Ft=window.navigator.connection,ts=()=>{const a=Ft?.downlink;if(A(a)&&a!==10)return a*1e3},is=()=>{const a=Ft?.rtt;if(A(a)&&a!==3e3)return a},ss=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Vt{throughput;rtt;subscription=new te;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Vt.load(Zi)||(e.useBrowserEstimation?ts():void 0)||Jr,i=Vt.load(es)??(e.useBrowserEstimation?is():void 0)??0;if(this.throughput$=new f(t),this.rtt$=new f(i),this.rttAdjustedThroughput$=new f(ss(t,i,e.rttPenaltyRequestSize)),this.throughput=xi.getSmoothedValue(t,-1,e),this.rtt=xi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=ts();n&&this.throughput.next(n);const o=is();A(o)&&this.rtt.next(o)};Ft&&"onchange"in Ft&&this.subscription.add(C(Ft,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{Ti.set(Zi,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{Ti.set(es,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add($e({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(v(({throughput:s,rtt:r})=>ss(s,r,e.rttPenaltyRequestSize)),J(s=>{const r=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-r)/r>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=re();const s=new te;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(C(e,"progress").pipe(le()).subscribe(r=>{t=r.loaded,i=re()}));break;case 1:case 0:s.add(C(e,"loadstart").subscribe(()=>{t=0,i=re()}));break}s.add(C(e,"loadend").subscribe(r=>{if(e.status===200){const n=r.loaded,o=re(),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,r=re(),n=0,o=re();const c=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},d=async({done:h,value:u})=>{h?(!t&&this.addRawSpeed(s,re()-r,1),this.concurrentDownloads.delete(e)):u&&(t?(re()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval&&re()-r<this.tuningConfig.lowLatency.separateByteSequenceInterval?n+=u.byteLength:(this.addRawSpeed(n,re()-r,this.concurrentDownloads.size,t),n=u.byteLength,r=re()),o=re()):(s+=u.byteLength,n+=u.byteLength,n>=this.tuningConfig.streamMinSampleSize&&re()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,re()-o,this.concurrentDownloads.size),n=0,o=re())),await i?.read().then(d,c))};this.concurrentDownloads.add(e),i?.read().then(d,c)}addRawSpeed(e,t,i=1,s=!1){if(s||Vt.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){const t=Ti.get(e);if(A(t))return parseInt(t,10)??void 0}}const as={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:5,separateByteSequenceInterval:100}},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:Re.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,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,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!0,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:ot.VP9,androidPreferredFormat:Ke.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Xr=a=>({..._s(a,as),configName:[...a.configName??[],...as.configName]});var rs=({seekState:a,position$:e})=>M(a.stateChangeEnded$.pipe(v(({to:t})=>t.state===Y.None?void 0:(t.position??NaN)/1e3),J(A)),e.pipe(J(()=>a.getState().state===Y.None))),Kr=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return w(e,`Wrong container or containerId {${a.container}}`),e};class an{subscription=new te;domContainer;providerContainer;chromecastInitializer;logger=new Rs;abrLogger=this.logger.createComponentLog("ABR");explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new oe(l.STOPPED),seekState:new oe({state:Y.None}),volume:new oe({volume:1,muted:!1}),videoTrack:new oe(void 0),autoVideoTrackSwitching:new oe(!0),autoVideoTrackLimits:new oe({}),isLooped:new oe(!1),playbackRate:new oe(1),externalTextTracks:new oe([]),internalTextTracks:new oe([]),currentTextTrack:new oe(void 0),textTrackCuesSettings:new oe({}),cameraOrientation:new oe({x:0,y:0})};info={playbackState$:new f(l.STOPPED),position$:new f(0),duration$:new f(1/0),muted$:new f(!1),volume$:new f(1),availableQualities$:new f([]),availableQualitiesFps$:new f({}),availableAudioTracks$:new f([]),isAudioAvailable$:new f(!0),currentQuality$:new f(void 0),isAutoQualityEnabled$:new f(!0),autoQualityLimitingAvailable$:new f(!1),autoQualityLimits$:new f({}),currentPlaybackRate$:new f(1),currentBuffer$:new f({start:0,end:0}),isBuffering$:new f(!0),isStalled$:new f(!1),isEnded$:new f(!1),isLooped$:new f(!1),isLive$:new f(void 0),canChangePlaybackSpeed$:new f(void 0),atLiveEdge$:new f(void 0),atLiveDurationEdge$:new f(void 0),liveTime$:new f(void 0),liveBufferTime$:new f(void 0),currentFormat$:new f(void 0),availableTextTracks$:new f([]),currentTextTrack$:new f(void 0),throughputEstimation$:new f(void 0),rttEstimation$:new f(void 0),videoBitrate$:new f(void 0),hostname$:new f(void 0),httpConnectionType$:new f(void 0),httpConnectionReused$:new f(void 0),surface$:new f(nt.NONE),chromecastState$:new f(ge.NOT_AVAILABLE),chromecastDeviceName$:new f(void 0),intrinsicVideoSize$:new f(void 0),availableSources$:new f(void 0),is3DVideo$:new f(!1)};events={inited$:new L,ready$:new L,started$:new L,playing$:new L,paused$:new L,stopped$:new L,willStart$:new L,willResume$:new L,willPause$:new L,willStop$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L};experimental={element$:new f(void 0),tuningConfigName$:new f([]),enableDebugTelemetry$:new f(!1),dumpTelemetry:ta};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Xr(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ms({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Vt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const r=Reflect.get(t,i,s);return typeof r!="function"?r:(...n)=>{try{return r.apply(t,n)}catch(o){const c=n.map(u=>JSON.stringify(u,(p,S)=>{const b=typeof S;return["number","string","boolean"].includes(b)?S:S===null?null:`<${b}>`})),d=`Player.${String(i)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:h,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Kr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new jr({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()===l.STOPPED&&e.startTransitionTo(l.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==l.PLAYING&&t.startTransitionTo(l.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?C(document,"visibilitychange").pipe(le()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==l.PAUSED&&e.startTransitionTo(l.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==l.STOPPED&&e.startTransitionTo(l.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:Y.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()===ge.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()===ge.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){w(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(s=>s.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){w(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&this.providerContainer?.providerOutput.availableTextTracks$.getValue().length===0?this.providerContainer?.providerOutput.availableTextTracks$.pipe(J(t=>t.length>0),le()).subscribe(t=>{t.find(i=>i.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find(t=>t.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(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(),r=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+r.x,y:s.y+r.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){w(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(j(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===Y.None?void 0:t.position;return A(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(M(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(v(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(J(({from:e})=>e===l.STOPPED),le()).subscribe(()=>{this.initedAt=re(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case l.READY:this.events.ready$.next();break;case l.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case l.PAUSED:this.events.paused$.next();break;case l.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case l.PAUSED:this.events.willPause$.next();break;case l.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case l.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState({...n,state:Y.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe(v(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(v(n=>n.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(v(n=>n.map(({quality:o})=>o).sort((o,c)=>Ut(o)?1:Ut(c)?-1:Nt(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(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).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(v(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($e({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:rs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(v(({isLive:n,position:o,isLowLatency:c})=>{const d=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),he(),ti(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add($e({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(v(({isLive:n,position:o,duration:c})=>n&&(Math.abs(c)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),he(),ti(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(v(n=>n.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(v(n=>n.volume),he()).subscribe(this.info.volume$)).add(rs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(M(e.providerOutput.endedEvent$.pipe(wt(!0)),e.providerOutput.seekedEvent$.pipe(wt(!1))).pipe(he()).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(v(n=>({id:n?`No${n}`:"NoProviders",category:R.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(le(),v(n=>n??re()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(le(),v(()=>re()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(le(),v(()=>re()-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 f(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new f(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(J(({to:n})=>n===l.PLAYING),le()).subscribe(()=>i.next(!1)));let s=0;const r=M(e.providerOutput.isBuffering$,t,i).pipe(v(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),he());this.subscription.add(r.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(M(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(M(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===ge.CONNECTED?h=nt.SECOND_SCREEN:c?n?h=nt.PIP:o?h=nt.FULLSCREEN:h=nt.INLINE:h=nt.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(v(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new te;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(J(i=>i.length>0),le()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Lt(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.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(M(this.desiredState.videoTrack.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(v(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const e=this.providerContainer?.providerOutput;w(this.providerContainer),w(e),ea(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Zs(t)),this.providerContainer.current$.subscribe(({type:t})=>Jt("provider",t)),e.duration$.subscribe(t=>Jt("duration",t)),e.availableVideoTracks$.pipe(J(t=>!!t.length),le()).subscribe(t=>Jt("tracks",t)),this.events.fatalError$.subscribe(new ze("fatalError")),this.events.managedError$.subscribe(new ze("managedError")),e.position$.subscribe(new ze("position")),e.currentVideoTrack$.pipe(v(t=>t?.quality)).subscribe(new ze("quality")),this.info.currentBuffer$.subscribe(new ze("buffer")),e.isBuffering$.subscribe(new ze("isBuffering"))].forEach(t=>this.subscription.add(t)),Jt("codecs",Hr())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.DOM,message:String(s)})})};this.subscription.add(M(C(document,"visibilitychange"),C(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",r=this.desiredState.playbackState.getState()===l.PLAYING,n=!!e&&!e?.released;s&&r?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const rn=`@vkontakte/videoplayer-core@${Is}`;export{ge as ChromecastState,Ht as HttpConnectionType,dn as Observable,l as PlaybackState,an as Player,rn as SDK_VERSION,cn as Subject,hn as Subscription,nt as Surface,Is as VERSION,un as ValueSubject,g as VideoFormat,ln as VideoQuality};
37
+ 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 lr{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 dr(this.params.fov,this.params.orientation),this.cameraRotationManager=new cr(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"),r=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(r,-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(ur,this.gl.VERTEX_SHADER),i=this.createShader(hr,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,r=e-i,n=t-s,o=e+i,c=t-s,d=e+i,h=t+s,u=e-i,p=t+s;return[r,n,o,c,d,h,u,p]}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}}class ls{scene3D;subscription=new te;videoState=new ne(oe.STOPPED);video;player;params;elementSize$=new m(void 0);textTracksManager=new Ge;droppedFramesManager=new di;videoTracks$=new m([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Zs;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Ke(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($e(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new or({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=et(this.video),s=this.constructor.name,r=o=>{e.error$.next({id:s,category:C.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:(o,c)=>this.subscription.add(o.subscribe(c,r))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:r}=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(y(d=>d.map(({track:h})=>h)))}),r(i.ended$,e.endedEvent$),r(i.looped$,e.loopedEvent$),r(i.error$,e.error$),r(i.isBuffering$,e.isBuffering$),r(i.currentBuffer$,e.currentBuffer$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.inPiP$,e.inPiP$),r(i.inFullscreen$,e.inFullscreen$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.isLive$,e.isLive$),r(this.player.lastRequestFirstBytes$.pipe(K(w),le()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(ft(this.video,t.isLooped,s)),this.subscription.add(Xe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,s)),r(ei(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),D(t.playbackState,l.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),D(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===Ce.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const u=this.player.getRepresentations();P(u,"Manifest not loaded or empty");const p=Array.from(u.audio).sort((v,R)=>R.bitrate-v.bitrate),f=Array.from(u.video).sort((v,R)=>R.bitrate-v.bitrate),b=Array.from(u.text);if(!this.params.tuning.isAudioDisabled)for(const v of p){const R=ir(v);R&&this.audioTracks.push({track:R,representation:v})}for(const v of f){const R=tr(v);if(R){h.push({track:R,representation:v});const N=!this.params.tuning.isAudioDisabled&&sr(p,f,v);N&&this.audioRepresentations.set(v.id,N)}}this.videoTracks$.next(h);for(const v of b){const R=ar(v);R&&this.textTracks.push({track:R,representation:v})}this.params.output.availableVideoTracks$.next(h.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));const E=this.selectVideoRepresentation();P(E),this.player.initRepresentations(E.id,this.audioRepresentations.get(E.id)?.id)}else d===Ce.REPRESENTATIOS_READY&&(this.videoState.setState(oe.READY),this.player.initBuffer())},s));const n=d=>e.error$.next({id:"RepresentationSwitch",category:C.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(B(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,L(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==Ce.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();if(p&&this.params.output.autoVideoTrackLimits$.next(p.to),u){this.player.switchRepresentation(Se.VIDEO,u.id).catch(n);const f=this.audioRepresentations.get(u.id);f&&this.player.switchRepresentation(Se.AUDIO,f.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(ce(),y(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(y(({to:d})=>d===l.READY),ce());this.subscription.add(B(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),u=t.playbackState.getState()===l.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(u)})),this.subscription.add(B(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===l.READY)));const c=B(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ee(["init"])).pipe(Ie(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),i=this.videoTracks$.getValue().find(({track:{id:u}})=>u===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),r=rt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(r/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=$t(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===H.Requested&&i?.to!==l.PAUSED&&e!==oe.STOPPED&&t!==l.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===l.STOPPED){e!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.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(oe.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}switch(e){case oe.STOPPED:this.videoState.startTransitionTo(oe.READY),this.prepare();return;case oe.READY:t===l.PAUSED?(this.videoState.setState(oe.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):i?.to===l.READY&&D(this.params.desiredState.playbackState,l.READY);return;case oe.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case oe.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(oe.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===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return M(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new lr(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(){ot(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(oe.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.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),Ze(this.video)}}class pr extends ls{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class fr extends ls{constructor(e){super(e),this.liveOffset=new oi}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(De({interval:Zt(vi),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===oe.PLAYING){const r=e.position$.getValue()+(s-1);e.position$.next(r),this.liveOffset?.resetTo(-r*1e3)}})).add(De({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(y(({liveBufferTime:s,liveAvailabilityStartTime:r})=>s&&r?s+r: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===l.PAUSED&&i===oe.PAUSED,r=-e,n=Math.trunc(r/1e3<=Math.abs(this.params.output.duration$.getValue())?r:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const Fe={};var X;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(X||(X={}));const Rt=(a,e)=>new ni(t=>{const i=(s,r)=>t.next(r);return a.on(e,i),()=>a.off(e,i)});class mr{subscription=new te;videoState=new ne(X.INITIALIZING);video;params;hls;textTracksManager=new Ge;trackLevels=new Map;constructor(e){this.video=Ke(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($e(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),Ze(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:C.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||(Fe.Hls=s.default,Fe.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(Fe.Hls,"hls.js not loaded"),this.hls=new Fe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){P(Fe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:C.WTF,message:"HlsJsProvider internal logic error",thrown:d})},s=et(this.video),r=(d,h)=>this.subscription.add(d.subscribe(h,i));r(s.timeUpdate$,t.position$),r(s.durationChange$,t.duration$),r(s.ended$,t.endedEvent$),r(s.looped$,t.loopedEvent$),r(s.error$,t.error$),r(s.isBuffering$,t.isBuffering$),r(s.currentBuffer$,t.currentBuffer$),r(s.loadStart$,t.firstBytesEvent$),r(s.playing$,t.firstFrameEvent$),r(s.canplay$,t.canplay$),r(s.seeked$,t.seekedEvent$),r(s.inPiP$,t.inPiP$),r(s.inFullscreen$,t.inFullscreen$),this.subscription.add(ft(this.video,e.isLooped,i)),this.subscription.add(Xe(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(nt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(Rt(this.hls,Fe.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:C.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(X.PLAYING),D(e.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),D(e.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===X.READY&&this.videoState.setState(X.READY),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},i)),r(Rt(this.hls,Fe.Events.MANIFEST_PARSED).pipe(y(({levels:d})=>d.reduce((h,u)=>{const p=u.name||u.height.toString(10),{width:f,height:b}=u,E=Vt(u.attrs.QUALITY??"")??pt({width:f,height:b});if(!E)return h;const v=u.attrs["FRAME-RATE"]?parseFloat(u.attrs["FRAME-RATE"]):void 0,R={id:p.toString(),quality:E,bitrate:u.bitrate/1e3,size:{width:f,height:b},fps:v};return this.trackLevels.set(p,{track:R,level:u}),h.push(R),h},[]))),t.availableVideoTracks$),r(Rt(this.hls,Fe.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const h=[];for(const u of d.subtitleTracks){const p=u.name,f=u.attrs.URI||"",b=u.lang,E="internal";h.push({id:p,url:f,language:b,type:E})}e.internalTextTracks.startTransitionTo(h)}}),r(Rt(this.hls,Fe.Events.LEVEL_LOADING).pipe(y(({url:d})=>$e(d))),t.hostname$),this.subscription.add(Ne(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=Rt(this.hls,Fe.Events.LEVEL_SWITCHED).pipe(y(({level:d})=>n(this.hls.levels[d])));o.pipe(K(w)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ne(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel])?.id,d=>{if(J(d))return;const h=this.trackLevels.get(d)?.level;if(!h)return;const u=this.hls.levels.indexOf(h),p=this.hls.currentLevel,f=this.hls.levels[p];!f||h.bitrate>f.bitrate?this.hls.nextLevel=u:(this.hls.loadLevel=u,this.hls.loadLevel=u)},{changed$:o.pipe(y(d=>d?.id)),onError:i})),r(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=B(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ee(["init"])).pipe(Ie(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!==X.INITIALIZING)switch(i?.to!==l.PAUSED&&s.state===H.Requested&&this.seek(s.position),t){case l.STOPPED:switch(e){case X.STOPPED:break;case X.READY:case X.PLAYING:case X.PAUSED:this.stop();break;default:M(e)}break;case l.READY:switch(e){case X.STOPPED:this.prepare();break;case X.READY:case X.PLAYING:case X.PAUSED:break;default:M(e)}break;case l.PLAYING:switch(e){case X.PLAYING:break;case X.STOPPED:this.prepare();break;case X.READY:case X.PAUSED:this.playIfAllowed();break;default:M(e)}break;case l.PAUSED:switch(e){case X.PAUSED:break;case X.STOPPED:this.prepare();break;case X.READY:this.videoState.setState(X.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED);break;case X.PLAYING:this.pause();break;default:M(e)}break;default:M(t)}};prepare(){this.videoState.startTransitionTo(X.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(X.PLAYING),await ot(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:t}))||(this.videoState.setState(X.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))}pause(){this.videoState.startTransitionTo(X.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(X.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0)}}const Ui="X-Playback-Duration";var Hi=async a=>{const e=await fetch(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Ui)?parseInt(e.headers.get(Ui),10):void 0};const gr=a=>{let e=null;if(a.QUALITY&&(e=Vt(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=pt({width:t,height:i})}return e??null},ps=async(a,e=a)=>{const s=(await(await fetch(a)).text()).split(`
38
+ `),r=[],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(N=>N.split("="))),p=u.QUALITY??`stream-${u.BANDWIDTH}`,f=gr(u);let b;u.BANDWIDTH&&(b=parseInt(u.BANDWIDTH,10)/1e3||void 0),!b&&u["AVERAGE-BANDWIDTH"]&&(b=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const E=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let v;if(u.RESOLUTION){const[N,g]=u.RESOLUTION.split("x").map($=>parseInt($,10));N&&g&&(v={width:N,height:g})}const R=new URL(s[++o],e).toString();f&&r.push({id:p,quality:f,url:R,bandwidth:b,size:v,fps:E})}if(h){const u=Object.fromEntries(h[1].split(",").map(E=>E.split("=")).map(([E,v])=>[E,v.replace(/^"|"$/g,"")])),p=u.URI?.replace(/playlist$/,"subtitles.vtt"),f=u.LANGUAGE,b=u.NAME;p&&f&&n.push({type:"internal",id:f,label:b,language:f,url:p,isAuto:!1})}}}return{qualityManifests:r,textTracks:n}};var se;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(se||(se={}));class Sr{subscription=new te;videoState=new ne(se.STOPPED);video;params;textTracksManager=new Ge;manifests$=new m([]);maxSeekBackTime$;liveOffset=new oi;manifestStartTime$=new m(void 0);constructor(e){this.params=e,this.video=Ke(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Re.INVARIANT,url:this.params.source.url};ps(Ye(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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($e(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(),r=s?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=et(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,i));r(s.ended$,e.endedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Xe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),D(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),D(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ce(),y(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&&w(d.to)){const u=d.to;this.params.desiredState.videoTrack.setState(u);const p=this.manifests$.getValue().find(f=>f.id===u);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next($e(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===se.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===H.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(De({startTime:this.manifestStartTime$.pipe(K(w)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),i)),this.subscription.add(this.manifests$.pipe(y(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:p})=>({id:c,quality:d,size:h,fps:p,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i));const n=B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,Ee(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}prepare(){const e=this.selectManifest();if(J(e))return;const t=this.params.format===S.HLS_LIVE_CMAF?fe.DASH_CMAF_OFFSET_P:fe.OFFSET_P,i=Ye(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),Hi(i).then(s=>{if(!J(s))this.maxSeekBackTime$.next(s);else{const r=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(J(r)||!isFinite(r))try{fetch(i).then(n=>n.text()).then(n=>{const o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n)?.[1];if(o){const c=new URL(o,i).toString();Hi(c).then(d=>{J(d)||this.maxSeekBackTime$.next(d)})}})}catch{}}})}playIfAllowed(){ot(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.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(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===l.STOPPED){t!==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),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(r||n){const d=this.videoState.getState();this.videoState.setState(se.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),c.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==l.PAUSED&&c.state===H.Requested){this.videoState.startTransitionTo(se.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case se.READY:i===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case se.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(se.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)):this.seek(-this.liveOffset.getTotalOffset())):s?.to===l.PAUSED&&(D(this.params.desiredState.playbackState,l.PAUSED),this.liveOffset.pause());return;case se.CHANGING_MANIFEST:break;default:return M(t)}}}var re;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(re||(re={}));class br{subscription=new te;videoState=new ne(re.STOPPED);video;params;textTracksManager=new Ge;manifests$=new m([]);constructor(e){this.params=e,this.video=Ke(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Re.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($e(this.params.source.url)),ps(this.params.source.url).then(({qualityManifests:i,textTracks:s})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),r=s?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},s=et(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c));if(r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(Xe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),D(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),D(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.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&&w(d.to)){const u=d.to;this.params.desiredState.videoTrack.setState(u);const p=this.manifests$.getValue().find(f=>f.id===u);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next($e(p.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===re.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===H.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(y(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:p})=>({id:c,quality:d,size:h,fps:p,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(B(L(o,"addtrack"),L(o,"removetrack"),L(o,"change"),Ee(["init"])).subscribe(()=>{for(let c=0;c<o.length;c++)o[c].mode="hidden"},i))}const n=B(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ee(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}prepare(){const e=this.selectManifest();J(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){ot(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.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(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===l.STOPPED){t!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(r||n){const d=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:h}=this.video;this.prepare(),c.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:h*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&c.state===H.Requested&&this.seek(c.position),t){case re.READY:i===l.READY?D(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(re.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):s?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case re.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return M(t)}}}var de;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(de||(de={}));class Tr{subscription=new te;videoState=new ne(de.STOPPED);video;trackUrls={};params;textTracksManager=new Ge;constructor(e){this.params=e,this.video=Ke(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const r=s.toString(10);this.trackUrls[r]={track:{quality:t,id:r},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:C.WTF,message:"MpegProvider internal logic error",thrown:o})},s=et(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,i));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(Xe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),D(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),D(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===de.READY&&this.videoState.setState(de.READY);const o=this.params.desiredState.videoTrack.getTransition();o&&w(o.to)&&(this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to].track)),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=B(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ee(["init"])).pipe(Ie(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),Ze(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();P(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];P(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next($e(t))}playIfAllowed(){ot(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.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===l.STOPPED){e!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(r&&e!==de.READY&&!n){this.handleQualityLimitTransition(r.to.max);return}if(e===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(n){const{currentTime:c}=this.video;this.prepare(),o.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:c*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==l.PAUSED&&o.state===H.Requested&&this.seek(o.position),e){case de.READY:t===l.READY?D(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(de.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):i?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case de.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return M(e)}};handleQualityLimitTransition(e){let t;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const i=Object.values(this.trackUrls).find(n=>ts(n.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState(),r=this.trackUrls[s??"0"]?.track;i&&r&&Si(r.quality,i.quality)&&(t=i)}else if(!e){const i=Object.values(this.trackUrls).map(s=>s.track);t=$t(i,{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.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const Yi=["stun:videostun.mycdn.me:80"],yr=1e3,vr=3,gi=()=>null;class Er{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=gi;externalStopCallback=gi;externalErrorCallback=gi;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:Yi}]};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:C.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),yr)}normalizeOptions(e={}){const t={stunServerList:Yi,maxRetryNumber:vr,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ae;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ae||(ae={}));class $r{subscription;params;log;video;videoState=new ne(ae.STOPPED);liveStreamClient;maxSeekBackTime$=new m(0);constructor(e){this.subscription=new te,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ke(e.container),this.liveStreamClient=new Er(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),Ze(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};B(this.videoState.stateChangeStarted$.pipe(y(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(y(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=et(this.video),r=(n,o)=>this.subscription.add(n.subscribe(o,i));r(s.timeUpdate$,e.liveTime$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(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===ae.READY&&this.videoState.setState(ae.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Xe(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ae.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(l.STOPPED);break;case ae.READY:break;case ae.PAUSED:t.playbackState.setState(l.PAUSED);break;case ae.PLAYING:t.playbackState.setState(l.PLAYING);break;default:return M(n.to)}},i)).add(B(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ee(["init"])).pipe(Ie(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($e(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:Re.INVARIANT}),this.video.srcObject=e,D(this.params.desiredState.playbackState,l.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ae.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:C.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ot(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.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===l.STOPPED){e!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),D(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition();if(e===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(r){this.prepare();return}switch(e){case ae.READY:t===l.PAUSED?(this.videoState.setState(ae.PAUSED),D(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed());return;case ae.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),this.video.pause()):i?.to===l.PLAYING&&D(this.params.desiredState.playbackState,l.PLAYING);return;case ae.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&D(this.params.desiredState.playbackState,l.PAUSED);return;default:return M(e)}}}class Gi{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 fs=$i().device===As.Android,ri=document.createElement("video"),kr='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ar='video/mp4; codecs="hev1.1.6.L93.B0"',ms='video/webm; codecs="vp09.00.10.08"',gs='video/webm; codecs="av01.0.00M.08"',wr='audio/mp4; codecs="mp4a.40.2"',Pr='audio/webm; codecs="opus"',Me={mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(ri.canPlayType?.("application/x-mpegurl")||ri.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},we={mp4:!!ri.canPlayType?.("video/mp4"),webm:!!ri.canPlayType?.("video/webm"),cmaf:!0},He={h264:!!window.MediaSource?.isTypeSupported?.(kr),h265:!!window.MediaSource?.isTypeSupported?.(Ar),vp9:!!window.MediaSource?.isTypeSupported?.(ms),av1:!!window.MediaSource?.isTypeSupported?.(gs),aac:!!window.MediaSource?.isTypeSupported?.(wr),opus:!!window.MediaSource?.isTypeSupported?.(Pr)},St=(He.h264||He.h265)&&He.aac;var at;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(at||(at={}));var Je;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg"})(Je||(Je={}));let ut;const Dr=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:gs}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:ms}})]);ut={[S.DASH_WEBM_AV1]:e,[S.DASH_WEBM]:t}};try{Dr()}catch(a){console.error(a)}const Ft=Me.hls&&we.mp4,_r=()=>Object.keys(He).filter(a=>He[a]),xr=(a,e=!1)=>a.filter(t=>{switch(t){case S.DASH:return Me.mse&&we.mp4&&St;case S.DASH_SEP:return Me.mse&&we.mp4&&St;case S.DASH_WEBM:return Me.mse&&we.webm&&He.vp9&&He.opus;case S.DASH_WEBM_AV1:return Me.mse&&we.webm&&He.av1&&He.opus;case S.DASH_LIVE:return Me.mse&&we.mp4&&St;case S.DASH_LIVE_CMAF:return Me.mse&&we.mp4&&St&&we.cmaf;case S.DASH_ONDEMAND:return Me.mse&&we.mp4&&St;case S.HLS:case S.HLS_ONDEMAND:return Ft||e&&Me.mse&&we.mp4&&St;case S.HLS_LIVE:case S.HLS_LIVE_CMAF:return Ft;case S.MPEG:return we.mp4;case S.DASH_LIVE_WEBM:return!1;case S.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&He.h264&&(we.mp4||we.webm);default:return M(t)}}),Ct=a=>{const e=S.DASH_WEBM,t=S.DASH_WEBM_AV1;switch(a){case at.VP9:return[e,t];case at.AV1:return[t,e];case at.NONE:return[];case at.SMOOTH:return ut?ut[t].smooth?[t,e]:ut[e].smooth?[e,t]:[t,e]:[e,t];case at.POWER_EFFICIENT:return ut?ut[t].powerEfficient?[t,e]:ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:M(a)}return[e,t]},Rr=({webmCodec:a,androidPreferredFormat:e})=>{if(fs)switch(e){case Je.MPEG:return[S.MPEG,...Ct(a),S.DASH_SEP,S.DASH,S.DASH_ONDEMAND,S.HLS,S.HLS_ONDEMAND];case Je.HLS:return[S.HLS,S.HLS_ONDEMAND,...Ct(a),S.DASH_SEP,S.DASH,S.DASH_ONDEMAND,S.MPEG];case Je.DASH:return[...Ct(a),S.DASH_SEP,S.DASH,S.DASH_ONDEMAND,S.HLS,S.HLS_ONDEMAND,S.MPEG]}return Ft?[...Ct(a),S.DASH_SEP,S.DASH_ONDEMAND,S.HLS,S.HLS_ONDEMAND,S.MPEG,S.DASH]:[...Ct(a),S.DASH_SEP,S.DASH,S.DASH_ONDEMAND,S.HLS,S.HLS_ONDEMAND,S.MPEG]},Cr=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{const i=e?[S.DASH_LIVE_CMAF,S.DASH_LIVE]:[S.DASH_LIVE,S.DASH_LIVE_CMAF],s=e?[S.HLS_LIVE_CMAF,S.HLS_LIVE]:[S.HLS_LIVE,S.HLS_LIVE_CMAF],r=[...i,...s],n=[...s,...i];let o;if(fs)switch(a){case Je.DASH:{o=r;break}case Je.HLS:case Je.MPEG:{o=n;break}}else Ft?o=n:o=r;return t?[S.WEB_RTC_LIVE,...o]:[...o,S.WEB_RTC_LIVE]},qi=a=>a?[S.HLS_LIVE,S.HLS_LIVE_CMAF,S.DASH_LIVE_CMAF]:[S.DASH_WEBM,S.DASH_WEBM_AV1,S.DASH_SEP,S.DASH_ONDEMAND,S.HLS,S.HLS_ONDEMAND,S.MPEG];var Lr=a=>new ni(e=>{const t=new te,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(y(({from:d,to:h})=>`${d}-${h}`)),s=a.desiredPlaybackState$.stateChangeEnded$,r=a.providerChanged$.pipe(y(({type:d})=>d!==void 0)),n=new x;let o=0,c="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),c="unknown",o=0})),t.add(r.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Ir={cacheDuration:12e4},Br={chunkDuration:5e3,maxParallelRequests:5};class Mr{current$=new m({type:void 0});providerError$=new x;noAvailableProvidersError$=new x;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 x,warning$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,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 te;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=xr([...Cr(this.params.tuning),...Rr(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>w(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let r=[];i?r=[i]:s.length?r=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:r=t,this.log({message:`Selected formats: ${r.join(" > ")}`}),this.screenFormatsIterator=new Gi(r);const n=[...qi(!0),...qi(!1)];this.chromecastFormatsIterator=new Gi(n.filter(o=>w(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(J(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:C.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!==H.None;if(this.params.desiredState.seekState.setState({state:H.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 r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Te.SCREEN:return this.createScreenProvider(t);case Te.CHROMECAST:return this.createChromecastProvider(t);default:return M(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,r=this.providerOutput,n={container:i,source:null,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case S.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new va({...n,source:o,config:Ir})}case S.DASH_SEP:case S.DASH_WEBM:case S.DASH_WEBM_AV1:case S.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new Li({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new pr({...n,source:o})}case S.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new Li({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new fr({...n,source:o})}case S.HLS:case S.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Ft||!this.params.tuning.useHlsJs?new br({...n,source:o}):new mr({...n,source:o})}case S.HLS_LIVE:case S.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Sr({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case S.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new Tr({...n,source:o})}case S.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new ga({...n,source:o,config:{...Br,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case S.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new $r({container:i,source:o,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case S.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Ns({connection:o,meta:r,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()?Te.CHROMECAST:Te.SCREEN}chooseFormat(e){switch(e){case Te.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Te.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return M(e)}}skipFormat(e){switch(e){case Te.SCREEN:return this.screenFormatsIterator.next();case Te.CHROMECAST:return this.chromecastFormatsIterator.next();default:return M(e)}}handleNoFormatsError(e){switch(e){case Te.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Te.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return M(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 r=new URL(s);return r.host=t,r.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,r])=>[s,i(r)]))}initProviderErrorHandling(){const e=new te;let t=!1,i=0;return e.add(B(this.providerOutput.error$,Lr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(y(s=>({id:`ProviderHangup:${s}`,category:C.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(K(({to:r})=>r===l.PLAYING),le()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const r=this.current$.getValue().destination;if(r===Te.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Te.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===C.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(r??Te.SCREEN)}})),e}}const Ei=(a,e,t)=>t*e+(1-t)*a,Ss=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Nr=(a,e,t,i)=>{let s=0,r=t;const n=Ss(a,e),o=e<i?e:i;for(let c=0;c<o;c++)a[r]>n?s++:s--,r=(a.length+r-1)%a.length;return Math.abs(s)===o};class bs{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 Ve(`raw_${t}`),this.smoothedSeries$=new Ve(`smoothed_${t}`),this.reportedSeries$=new Ve(`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),r=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>r||this.smoothed<n)&&(J(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 Or extends bs{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ei(this.slow,e,this.params.emaAlphaSlow),this.fast=Ei(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Fr extends bs{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Ss(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ei(this.emaSmoothed,e,this.params.emaAlpha);const i=Nr(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class zi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Or({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Fr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const Vr=5e3,Wi="one_video_throughput",Qi="one_video_rtt",Bt=window.navigator.connection,ji=()=>{const a=Bt?.downlink;if(w(a)&&a!==10)return a*1e3},Ji=()=>{const a=Bt?.rtt;if(w(a)&&a!==3e3)return a},Xi=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Mt{throughput;rtt;subscription=new te;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Mt.load(Wi)||(e.useBrowserEstimation?ji():void 0)||Vr,i=Mt.load(Qi)??(e.useBrowserEstimation?Ji():void 0)??0;if(this.throughput$=new m(t),this.rtt$=new m(i),this.rttAdjustedThroughput$=new m(Xi(t,i,e.rttPenaltyRequestSize)),this.throughput=zi.getSmoothedValue(t,-1,e),this.rtt=zi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=ji();n&&this.throughput.next(n);const o=Ji();w(o)&&this.rtt.next(o)};Bt&&"onchange"in Bt&&this.subscription.add(L(Bt,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{fi.set(Wi,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{fi.set(Qi,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(De({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(y(({throughput:s,rtt:r})=>Xi(s,r,e.rttPenaltyRequestSize)),K(s=>{const r=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-r)/r>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ue();const s=new te;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(L(e,"progress").pipe(le()).subscribe(r=>{t=r.loaded,i=ue()}));break;case 1:case 0:s.add(L(e,"loadstart").subscribe(()=>{t=0,i=ue()}));break}s.add(L(e,"loadend").subscribe(r=>{if(e.status===200){const n=r.loaded,o=ue(),c=n-t,d=o-i;this.addRawSpeed(c,d,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const s=ue();let r=0,n=ue();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=async({done:d,value:h})=>{d?(this.addRawSpeed(i,ue()-s,1),this.concurrentDownloads.delete(e)):h&&(i+=h.byteLength,r+=h.byteLength,r>=this.tuningConfig.streamMinSampleSize&&ue()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,ue()-n,this.concurrentDownloads.size),r=0,n=ue()),await t?.read().then(c,o))};this.concurrentDownloads.add(e),t?.read().then(c,o)}addRawSpeed(e,t,i=1){if(Mt.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){const t=fi.get(e);if(w(t))return parseInt(t,10)??void 0}}const Ki={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},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:Re.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},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:at.VP9,androidPreferredFormat:Je.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Ur=a=>({...ws(a,Ki),configName:[...a.configName??[],...Ki.configName]});var Zi=({seekState:a,position$:e})=>B(a.stateChangeEnded$.pipe(y(({to:t})=>t.state===H.None?void 0:(t.position??NaN)/1e3),K(w)),e.pipe(K(()=>a.getState().state===H.None))),Hr=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return P(e,`Wrong container or containerId {${a.container}}`),e};class Wr{subscription=new te;domContainer;providerContainer;chromecastInitializer;logger=new Ps;abrLogger=this.logger.createComponentLog("ABR");explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new ne(l.STOPPED),seekState:new ne({state:H.None}),volume:new ne({volume:1,muted:!1}),videoTrack:new ne(void 0),autoVideoTrackSwitching:new ne(!0),autoVideoTrackLimits:new ne({}),isLooped:new ne(!1),playbackRate:new ne(1),externalTextTracks:new ne([]),internalTextTracks:new ne([]),currentTextTrack:new ne(void 0),textTrackCuesSettings:new ne({}),cameraOrientation:new ne({x:0,y:0})};info={playbackState$:new m(l.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(st.NONE),chromecastState$:new m(ge.NOT_AVAILABLE),chromecastDeviceName$:new m(void 0),intrinsicVideoSize$:new m(void 0),availableSources$:new m(void 0),is3DVideo$:new m(!1)};events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x};experimental={element$:new m(void 0),tuningConfigName$:new m([]),enableDebugTelemetry$:new m(!1),dumpTelemetry:Js};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Ur(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Rs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Mt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const r=Reflect.get(t,i,s);return typeof r!="function"?r:(...n)=>{try{return r.apply(t,n)}catch(o){const c=n.map(u=>JSON.stringify(u,(p,f)=>{const b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),d=`Player.${String(i)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:C.WTF,message:h,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Hr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Mr({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()===l.STOPPED&&e.startTransitionTo(l.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==l.PLAYING&&t.startTransitionTo(l.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?L(document,"visibilitychange").pipe(le()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==l.PAUSED&&e.startTransitionTo(l.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==l.STOPPED&&e.startTransitionTo(l.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:H.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()===ge.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()===ge.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(s=>s.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){P(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 e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&this.providerContainer?.providerOutput.availableTextTracks$.getValue().length===0?this.providerContainer?.providerOutput.availableTextTracks$.pipe(K(t=>t.length>0),le()).subscribe(t=>{t.find(i=>i.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find(t=>t.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(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(),r=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+r.x,y:s.y+r.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(J(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===H.None?void 0:t.position;return w(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(B(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(y(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(y(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(y(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(y(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(y(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(K(({from:e})=>e===l.STOPPED),le()).subscribe(()=>{this.initedAt=ue(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case l.READY:this.events.ready$.next();break;case l.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case l.PAUSED:this.events.paused$.next();break;case l.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case l.PAUSED:this.events.willPause$.next();break;case l.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case l.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===H.Requested?this.desiredState.seekState.setState({...n,state:H.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===H.Applying&&(this.desiredState.seekState.setState({state:H.None}),this.events.seeked$.next())})).add(e.current$.pipe(y(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(y(n=>n.destination),ce()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(y(n=>n.map(({quality:o})=>o).sort((o,c)=>Nt(o)?1:Nt(c)?-1:It(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(ce()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ce()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ce()).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(y(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(De({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zi({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(y(({isLive:n,position:o,isLowLatency:c})=>{const d=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ce(),Kt(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(De({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(y(({isLive:n,position:o,duration:c})=>n&&Math.abs(c)-Math.abs(o)<this.tuning.live.activeLiveDelay),ce(),Kt(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(y(n=>n.muted),ce()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(y(n=>n.volume),ce()).subscribe(this.info.volume$)).add(Zi({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(B(e.providerOutput.endedEvent$.pipe(Tt(!0)),e.providerOutput.seekedEvent$.pipe(Tt(!1))).pipe(ce()).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(y(n=>({id:n?`No${n}`:"NoProviders",category:C.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(le(),y(n=>n??ue()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(le(),y(()=>ue()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(le(),y(()=>ue()-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===l.PLAYING),le()).subscribe(()=>i.next(!1)));let s=0;const r=B(e.providerOutput.isBuffering$,t,i).pipe(y(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ce());this.subscription.add(r.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(B(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(B(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===ge.CONNECTED?h=st.SECOND_SCREEN:c?n?h=st.PIP:o?h=st.FULLSCREEN:h=st.INLINE:h=st.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(y(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new te;this.subscription.add(t),this.subscription.add(e.current$.pipe(ce((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),le()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=$t(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.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(B(this.desiredState.videoTrack.stateChangeStarted$.pipe(y(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(y(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(y(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(y(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(y(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(y(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(y(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(y(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(y(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;P(this.providerContainer),P(e),js(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Qs(t)),this.providerContainer.current$.subscribe(({type:t})=>zt("provider",t)),e.duration$.subscribe(t=>zt("duration",t)),e.availableVideoTracks$.pipe(K(t=>!!t.length),le()).subscribe(t=>zt("tracks",t)),this.events.fatalError$.subscribe(new Ve("fatalError")),this.events.managedError$.subscribe(new Ve("managedError")),e.position$.subscribe(new Ve("position")),e.currentVideoTrack$.pipe(y(t=>t?.quality)).subscribe(new Ve("quality")),this.info.currentBuffer$.subscribe(new Ve("buffer")),e.isBuffering$.subscribe(new Ve("isBuffering"))].forEach(t=>this.subscription.add(t)),zt("codecs",_r())}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:C.DOM,message:String(s)})})};this.subscription.add(B(L(document,"visibilitychange"),L(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",r=this.desiredState.playbackState.getState()===l.PLAYING,n=!!e&&!e?.released;s&&r?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const Qr=`@vkontakte/videoplayer-core@${_s}`;export{ge as ChromecastState,Ot as HttpConnectionType,Xr as Observable,l as PlaybackState,Wr as Player,Qr as SDK_VERSION,Kr as Subject,Zr as Subscription,st as Surface,_s as VERSION,en as ValueSubject,S as VideoFormat,tn as VideoQuality};